std-type

HashMap Entry — occupied or vacant

An Entry represents one position in a mutably borrowed map. Match Occupied and Vacant when the two cases need different actions. OccupiedEntry exposes the old value; VacantEntry can insert a new one. Expected stdout (not executed): 8 1 Common mistake: Trying to access the map independently while an entry handle is still needed.

Formal Syntax & Structure

rust syntaxrust
Entry<'a, K, V>

Working Example

Example Snippetrust
fn main() {    use std::collections::{HashMap, hash_map::Entry};    let mut m = HashMap::from([("a", 4)]);    for key in ["a", "b"] {        match m.entry(key) {            Entry::Occupied(mut e) => { *e.get_mut() *= 2; }            Entry::Vacant(e) => { e.insert(1); }        }    }    println!("{} {}", m["a"], m["b"]);}
Rust Reference