std-method

btree_map::Entry::and_modify

Apply a change only to an existing record and return the handle, allowing a fallback insertion to follow. Expected stdout (not executed): 10 2 Common mistake: Assuming and_modify alone inserts missing keys.

Formal Syntax & Structure

rust syntaxrust
fn and_modify<F: FnOnce(&mut V)>(self, f: F) -> Entry<'a, K, V>

Working Example

Example Snippetrust
fn main() {    use std::collections::BTreeMap;    let mut points = BTreeMap::from([("Ada", 8)]);    for name in ["Ada", "Lee"] { points.entry(name).and_modify(|p| *p += 2).or_insert(2); }    println!("{} {}", points["Ada"], points["Lee"]);}
Rust Reference