std-method

HashMap::get_mut

Borrow an existing value mutably to edit it in place. No key is created when the query misses. The returned reference temporarily restricts access to the map. Expected stdout (not executed): Some(6) None Common mistake: Holding the returned mutable reference while inserting into the map.

Formal Syntax & Structure

rust syntaxrust
pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V> where K: Borrow<Q>, Q: Hash + Eq

Working Example

Example Snippetrust
fn main() {    use std::collections::HashMap;    let mut stock = HashMap::from([("ticket", 8)]);    if let Some(n) = stock.get_mut("ticket") { *n -= 2; }    println!("{:?} {:?}", stock.get("ticket"), stock.get("vip"));}
Rust Reference