std-method

btree_map::Entry::or_insert

Provide a fallback value for an absent record, or borrow the existing value mutably. The argument is evaluated even if the entry is occupied. Expected stdout (not executed): 6 3 Common mistake: Assuming the fallback overwrites an existing value.

Formal Syntax & Structure

rust syntaxrust
fn or_insert(self, default: V) -> &'a mut V

Working Example

Example Snippetrust
fn main() {    use std::collections::BTreeMap;    let mut hours = BTreeMap::from([("Mon", 4)]);    *hours.entry("Mon").or_insert(1) += 2;    *hours.entry("Tue").or_insert(1) += 2;    println!("{} {}", hours["Mon"], hours["Tue"]);}
Rust Reference