Trait try_insert_ext::EntryInsertExt[][src]

pub trait EntryInsertExt<'a, K, V> {
    fn or_try_insert_with<F: FnOnce() -> Result<V, E>, E>(
        self,
        default: F
    ) -> Result<&'a mut V, E>;
fn or_try_insert_with_key<F: FnOnce(&K) -> Result<V, E>, E>(
        self,
        default: F
    ) -> Result<&'a mut V, E>; }

Extends map entries with or_try_insert_with and or_try_insert_with_key.

Required methods

fn or_try_insert_with<F: FnOnce() -> Result<V, E>, E>(
    self,
    default: F
) -> Result<&'a mut V, E>
[src]

If empty, computes the value from the default function. If the function returns Ok, inserts the value. If f returns Err, returns the error. If there is no error, returns a mutable reference to the value in the entry.

Examples

use std::collections::HashMap;

use try_insert_ext::EntryInsertExt;

let mut map: HashMap<&str, String> = HashMap::new();
let s = "hoho".to_string();

let e: Result<&mut String, ()> = map
    .entry("poneyland")
    .or_try_insert_with(|| Err(()));
assert!(e.is_err());
map.entry("poneyland").or_try_insert_with::<_, ()>(|| Ok(s));

assert_eq!(map["poneyland"], "hoho".to_string());

fn or_try_insert_with_key<F: FnOnce(&K) -> Result<V, E>, E>(
    self,
    default: F
) -> Result<&'a mut V, E>
[src]

If empty, computes the value from the default function. If the function returns Ok, inserts the value. If f returns Err, returns the error. If there is no error, returns a mutable reference to the value in the entry. This method allows for generating key-derived values for insertion by providing the default function a reference to the key that was moved during the .entry(key) method call.

Examples

use std::collections::HashMap;

use try_insert_ext::EntryInsertExt;

let mut map: HashMap<&str, usize> = HashMap::new();

let e: Result<&mut usize, ()> = map
    .entry("poneyland")
    .or_try_insert_with_key(|_| Err(()));
assert!(e.is_err());
map
    .entry("poneyland")
    .or_try_insert_with_key::<_, ()>(|key| Ok(key.chars().count()));

assert_eq!(map["poneyland"], 9);
Loading content...

Implementations on Foreign Types

impl<'a, K, V> EntryInsertExt<'a, K, V> for Entry<'a, K, V> where
    K: Ord
[src]

impl<'a, K, V> EntryInsertExt<'a, K, V> for Entry<'a, K, V>[src]

Loading content...

Implementors

Loading content...