pub struct OptionGuard<'a, T: 'a> { /* private fields */ }
Expand description
An option which has had its value taken. On Drop
, OptionGuard
will panic - in order to
prevent a panic, the stolen value must be moved back in with OptionGuard::restore
.
This is useful if you are using an Option
because you have a value which you need to take,
and then deal with by-value, but you want to preserve the invariant that your optional value is
always present.
§Examples
Calling guard.restore()
puts the stolen value back into the original option:
// 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));
But, if the guard is dropped instead, a runtime panic results.
ⓘ
let mut thing = Some(5);
let (_, _) = thing.steal();
// Never return the value!
Calling .steal()
on a None
immediately panics:
ⓘ
let mut thing = None;
// Panics here!
let (guard, _) = thing.steal();
guard.restore(5);
Implementations§
Source§impl<'a, T> OptionGuard<'a, T>
impl<'a, T> OptionGuard<'a, T>
Trait Implementations§
Auto Trait Implementations§
impl<'a, T> Freeze for OptionGuard<'a, T>
impl<'a, T> RefUnwindSafe for OptionGuard<'a, T>where
T: RefUnwindSafe,
impl<'a, T> Send for OptionGuard<'a, T>where
T: Send,
impl<'a, T> Sync for OptionGuard<'a, T>where
T: Sync,
impl<'a, T> Unpin for OptionGuard<'a, T>
impl<'a, T> !UnwindSafe for OptionGuard<'a, T>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more