Trait OptionInsertExt

Source
pub trait OptionInsertExt<T> {
    // Required method
    fn get_or_try_insert_with<F, E>(&mut self, f: F) -> Result<&mut T, E>
       where F: FnOnce() -> Result<T, E>;
}
Expand description

Extends Option with get_or_try_insert_with.

Required Methods§

Source

fn get_or_try_insert_with<F, E>(&mut self, f: F) -> Result<&mut T, E>
where F: FnOnce() -> Result<T, E>,

If the option is None, computes the value from f. If f returns Ok, inserts the value. If f returns Err, returns the error. If there is no error, returns a mutable reference to the contained value.

§Examples
use try_insert_ext::OptionInsertExt;

let mut x = None;

{
    let e: Result<&mut u32, ()> = x.get_or_try_insert_with(|| Err(()));
    assert!(e.is_err());
    let y: Result<&mut u32, ()> = x.get_or_try_insert_with(|| Ok(5));
    assert_eq!(y, Ok(&mut 5));

    *y.unwrap() = 7;
}

assert_eq!(x, Some(7));

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl<T> OptionInsertExt<T> for Option<T>

Source§

fn get_or_try_insert_with<F, E>(&mut self, f: F) -> Result<&mut T, E>
where F: FnOnce() -> Result<T, E>,

Implementors§