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.
Code
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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.