2个版本
使用旧的Rust 2015
| 0.1.1 | 2017年6月16日 |
|---|---|
| 0.1.0 | 2017年6月16日 |
#2091 在 Rust模式
15KB
117 行
empty-option: 用于从可变引用的Option中安全地获取和处理值的保护器
这个crate提供方便的包装器来处理&mut Option<T>。有两个主要类型,OptionGuard 和 OptionGuardMut
OptionGuard
在EmptyOptionExt::steal上对一个&mut Option<T>调用会产生来自选项的T以及一个OptionGuard。如果在OptionGuard销毁之前没有调用OptionGuard::restore,则会发生panic。
示例
调用guard.restore()将窃取的值放回原始选项中
use empty_option::EmptyOptionExt;
// A mutable option, from which we shall steal a value!
let mut thing = Some(5);
// Scope so that when we do `guard.restore()`, the mutable borrow on `thing` will end.
{
// Steal the value - we now have the guard and also a concrete `T` from our `Option<T>`.
let (guard, five) = thing.steal();
assert_eq!(five, 5);
// Move the value back into `thing` - we're done.
guard.restore(6);
}
// The value is returned by `guard.restore()`.
assert_eq!(thing, Some(6));
但如果守护者被丢弃,则会引发运行时panic。
use empty_option::EmptyOptionExt;
let mut thing = Some(5);
let (_, _) = thing.steal();
// Never return the value!
对None调用.steal()将立即panic
let mut thing = None;
// Panics here!
let (guard, _) = thing.steal();
guard.restore(5);
OptionGuardMut
在&mut Option<T>上使用EmptyOptionExt::steal_mut会产生一个OptionGuardMut,它解引用到一个T。要获取内部值,可以调用OptionGuardMut::into_inner。在Drop时,如果未使用OptionGuardMut::into_inner消耗OptionGuardMut,则其值将返回到它所借用的Option中。
示例
从一个选项中获取值,该值将自动返回
use empty_option::EmptyOptionExt;
let mut thing = Some(5);
{
let mut stolen = thing.steal_mut();
assert_eq!(*stolen, 5);
*stolen = 6;
}
assert_eq!(thing, Some(6));
如果守卫被消耗,则值永远不会返回。
use empty_option::EmptyOptionExt;
let mut thing = Some(5);
{
// Keep the thing!
let stolen = thing.steal_mut().into_inner();
assert_eq!(stolen, 5);
}
assert_eq!(thing, None);
在对steal_mut一个None调用时会立即触发panic
let mut thing: Option<i32> = None;
// Panics here!
thing.steal_mut();
许可证
许可协议为以下之一
- Apache License,Version 2.0,(LICENSE-APACHE 或 https://apache.ac.cn/licenses/LICENSE-2.0)
- MIT许可(LICENSE-MIT 或 https://open-source.org.cn/licenses/MIT)
根据您的选择。
贡献
除非您明确声明,否则您有意提交的任何贡献,根据Apache-2.0许可证的定义,应按照上述方式双许可,不附加任何额外条款或条件。