std-method
Entry::or_insert_with
Return mutable access to the value, invoking the supplied closure only when the entry is vacant. Use it for expensive initialization or computation with side effects. Expected stdout (not executed): 1 0 Common mistake: Using or_insert(expensive()) and expecting the expression to be lazy.
Formal Syntax & Structure
rust syntaxrust
pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut VWorking Example
Example Snippetrust
fn main() { use std::collections::HashMap; let mut m = HashMap::from([("ready", 7)]); let mut calls = 0; for key in ["ready", "new", "new"] { m.entry(key).or_insert_with(|| { calls += 1; 0 }); } println!("{} {}", calls, m["new"]);}