std-method

btree_map::Entry::or_insert_with

Delay default construction until a missing entry needs it. The closure is not invoked for an already present key. Expected stdout (not executed): 1 new Common mistake: Calling an expensive function before passing it to the closure.

Formal Syntax & Structure

rust syntaxrust
fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V

Working Example

Example Snippetrust
fn main() {    use std::collections::BTreeMap;    let mut files = BTreeMap::from([("a", String::from("cached"))]);    let mut builds = 0;    files.entry("a").or_insert_with(|| { builds += 1; String::new() });    files.entry("b").or_insert_with(|| { builds += 1; String::from("new") });    println!("{builds} {}", files["b"]);}
Rust Reference