Skip to main content

EntryInsertExt

Trait EntryInsertExt 

Source
pub trait EntryInsertExt<'a, K, V> {
    // Required methods
    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>;
}
Expand description

Extends map entries with or_try_insert_with and or_try_insert_with_key.

Required Methods§

Source

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

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

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

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

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementations on Foreign Types§

Source§

impl<'a, K, V> EntryInsertExt<'a, K, V> for Entry<'a, K, V>

Available on crate feature std only.
Source§

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

Source§

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

Source§

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

Available on crate feature std only.
Source§

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

Source§

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

Implementors§