Trait SetInsertExt

Source
pub trait SetInsertExt<T> {
    // Required method
    fn get_or_try_insert_with<Q, F, E>(
        &mut self,
        value: &Q,
        f: F,
    ) -> Result<&T, E>
       where T: Borrow<Q>,
             Q: Hash + Eq + ?Sized,
             F: FnOnce(&Q) -> Result<T, E>;
}
Expand description

Extends sets with get_or_try_insert_with.

Required Methods§

Source

fn get_or_try_insert_with<Q, F, E>(&mut self, value: &Q, f: F) -> Result<&T, E>
where T: Borrow<Q>, Q: Hash + Eq + ?Sized, F: FnOnce(&Q) -> Result<T, E>,

If the set does not contain the value, 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 reference to the contained value.

§Examples
use std::collections::HashSet;

use try_insert_ext::SetInsertExt;

let mut set: HashSet<String> = ["cat", "dog", "horse"]
    .iter()
    .map(|&pet| pet.to_owned())
    .collect();

assert_eq!(set.len(), 3);
let value = set.get_or_try_insert_with("error", |_| Err(()));
assert!(value.is_err());
for &pet in &["cat", "dog", "fish"] {
    let value = set.get_or_try_insert_with::<_, _, ()>(
        pet,
        |pet| Ok(pet.to_owned()),
    );
    assert_eq!(value, Ok(&pet.to_owned()));
}

assert_eq!(set.len(), 4);

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, S> SetInsertExt<T> for HashSet<T, S>
where T: Eq + Hash, S: BuildHasher,

Source§

fn get_or_try_insert_with<Q, F, E>(&mut self, value: &Q, f: F) -> Result<&T, E>
where T: Borrow<Q>, Q: Hash + Eq + ?Sized, F: FnOnce(&Q) -> Result<T, E>,

Implementors§