Match Occupied And Vacant Entries

Match counts.entry(key) on Occupied and Vacant: vacant slots insert, occupied slots mutate in place via get_mut, one probe per lookup.

RustData Integrity

Code

rustsnippet
30 lines
use std::collections::hash_map::Entry;
use std::collections::HashMap;

fn main() {
    let mut counts: HashMap<&str, u32> = HashMap::new();

    for word in ["alpha", "beta", "alpha", "gamma", "beta", "alpha"] {
        // match Entry:Vacant 首次插入,Occupied 拿到已有槽位就地更新
        match counts.entry(word) {
            Entry::Vacant(slot) => {
                slot.insert(1);
            }
            Entry::Occupied(mut slot) => {
                *slot.get_mut() += 1;
            }
        }
    }

    // into_mut 把借用升级成挂在 map 上的 &mut:返回值可直接改
    match counts.entry("delta") {
        Entry::Vacant(slot) => {
            let value = slot.into_mut();
            *value = 7;
        }
        Entry::Occupied(_) => unreachable!("delta starts empty"),
    }

    println!("alpha: {}", counts["alpha"]);
    println!("delta: {}", counts["delta"]);
}

How it works

Count the function main as the entire surface area of Match Occupied And Vacant Entries.

Iteration happens inside for word in ["alpha", "beta", "alpha", "gamma", "beta", "alpha"] — everything outside it runs once. match here is the control flow: arms enumerate the value’s shapes exhaustively.

Putting it to use

Output lines are prefixed (alpha:, delta:), making each step’s effect easy to spot.

Core lines

Entry::Occupied(mut slot) => {
    *slot.get_mut() += 1;
}
match counts.entry("delta") {
    Entry::Vacant(slot) => {
        let value = slot.into_mut();
        *value = 7;
    }
    Entry::Occupied(_) => unreachable!("delta starts empty"),
}
Entry::Vacant(slot) => {
    slot.insert(1);
}

Interactive Tools for This Topic

FAQ

What does Match Occupied And Vacant Entries print when run?
Invoke the file as-is — the `alpha:`, `delta:` prefixes identify which step printed each line.