Struct empty_option::OptionGuard [] [src]

pub struct OptionGuard<'a, T: 'a> { /* fields omitted */ }

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);

Methods

impl<'a, T> OptionGuard<'a, T>
[src]

Restore a stolen value to an Option.

Trait Implementations

impl<'a, T> Drop for OptionGuard<'a, T>
[src]

A method called when the value goes out of scope. Read more