BTreeMap Entry Insert Or Update

Match BTreeMap::entry to insert or update in one lookup, then read the map back in sorted key order without re-sorting.

RustData Integrity

Code

rustsnippet
23 lines
use std::collections::btree_map::Entry;
use std::collections::BTreeMap;

fn main() {
    let mut stock = BTreeMap::from([("widget", 4u32)]);

    // entry is one lookup: match it to insert or update in place
    for item in ["widget", "gadget", "widget"] {
        match stock.entry(item) {
            Entry::Occupied(mut slot) => {
                *slot.get_mut() += 2;
            }
            Entry::Vacant(slot) => {
                slot.insert(1);
            }
        }
    }

    // BTreeMap iteration is sorted by key, no re-sort needed
    for (name, count) in &stock {
        println!("{name}: {count}");
    }
}

Inside the snippet

BTreeMap Entry Insert Or Update comes down to the function main.

Repetition is confined to for item in ["widget", "gadget", "widget"] — the rest of the file is straight-line. The match expression is exhaustive — the compiler enforces that no case is missing.

Key statements

Entry::Occupied(mut slot) => {
    *slot.get_mut() += 2;
}
Entry::Vacant(slot) => {
    slot.insert(1);
}

Interactive Tools for This Topic

FAQ

How do you run BTreeMap Entry Insert Or Update?
Run it as a complete program — compile or interpret the file directly; there is nothing to install first.