Trait try_insert_ext::SetInsertExt[][src]

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

Extends sets with get_or_try_insert_with.

Required methods

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

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);
Loading content...

Implementations on Foreign Types

impl<T, S> SetInsertExt<T> for HashSet<T, S> where
    T: Eq + Hash,
    S: BuildHasher
[src]

Loading content...

Implementors

Loading content...