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.
Code
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
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
- 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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.