std-method

Entry::and_modify

Apply a closure only to an occupied entry, then return the entry handle so initialization can follow. A vacant entry is unchanged unless a later operation inserts it. Expected stdout (not executed): 6 1 Common mistake: Expecting and_modify alone to insert a missing key.

Formal Syntax & Structure

rust syntaxrust
pub fn and_modify<F: FnOnce(&mut V)>(self, f: F) -> Self

Working Example

Example Snippetrust
fn main() {    use std::collections::HashMap;    let mut m = HashMap::from([("a", 4)]);    for key in ["a", "b"] { m.entry(key).and_modify(|v| *v += 2).or_insert(1); }    println!("{} {}", m["a"], m["b"]);}
Rust Reference