HashMap Entry API Upserts
Insert-or-update in one lookup with the entry API, avoiding double hashing and the borrow-checker workarounds of get-then-insert.
Code
use std::collections::HashMap;
fn main() {
let words = ["alpha", "beta", "alpha", "gamma", "beta", "alpha"];
let mut counts: HashMap<&str, usize> = HashMap::new();
// entry().or_insert():一次查找完成插入或更新
for word in words {
*counts.entry(word).or_insert(0) += 1;
}
println!("counts: {:?}", counts);
// or_insert_with:惰性构造默认值(昂贵默认值时不白算)
let mut buckets: HashMap<char, Vec<&str>> = HashMap::new();
for word in words {
buckets
.entry(word.chars().next().unwrap())
.or_insert_with(Vec::new)
.push(word);
}
println!("buckets: {:?}", buckets);
// and_modify 链式:先改再兜底
let mut scores: HashMap<&str, i32> = HashMap::new();
scores.entry("ada").and_modify(|s| *s += 10).or_insert(5);
scores.entry("ada").and_modify(|s| *s += 10).or_insert(5);
println!("ada score: {:?}", scores.get("ada"));
}How the snippet works
HashMap Entry API Upserts is built around the function main.
Repetition is confined to for word in words — the rest of the file is straight-line.
Applying it
The demo output is labeled (counts:, buckets:, ada score:), so every printed line maps back to its originating operation.
Statements that matter
scores.entry("ada").and_modify(|s| *s += 10).or_insert(5);
.entry(word.chars().next().unwrap())
.or_insert_with(Vec::new)
.push(word);
Interactive Tools for This Topic
FAQ
- What does HashMap Entry API Upserts print when run?
- Invoke the file as-is — the `counts:`, `buckets:`, `ada score:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.