std-method
Entry::or_insert_with_key
Initialize a missing entry from a shared reference to its candidate key. The closure is skipped if an equivalent key already exists. This avoids cloning the key solely to compute a value. Expected stdout (not executed): 4 Common mistake: Trying to move the key out of the closure’s borrowed argument.
Formal Syntax & Structure
rust syntaxrust
pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut VWorking Example
Example Snippetrust
fn main() { use std::collections::HashMap; let mut m: HashMap<String, usize> = HashMap::new(); m.entry(String::from("book")).or_insert_with_key(|k| k.len()); println!("{}", m["book"]);}