std-method

BTreeMap::get_mut

Modify the value of an existing record without adding a missing one. Use the returned mutable reference only while the map can remain exclusively borrowed. Expected stdout (not executed): 9 Common mistake: Expecting get_mut to insert a missing entry.

Formal Syntax & Structure

rust syntaxrust
fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V> where K: Borrow<Q> + Ord, Q: Ord + ?Sized

Working Example

Example Snippetrust
fn main() {    use std::collections::BTreeMap;    let mut points = BTreeMap::from([("Mina", 7)]);    if let Some(score) = points.get_mut("Mina") { *score += 2; }    println!("{}", points["Mina"]);}
Rust Reference