Entry And Modify Upserts In One Lookup
and_modify updates existing entries in place while or_insert_with lazily builds initial values, completing an upsert with a single hash lookup.
Code
use std::collections::HashMap;
fn main() {
let mut stock: HashMap<&str, u32> = HashMap::new();
// and_modify:键已存在时就地更新;or_insert_with:缺失时才构造初值
for (item, delta) in [("pen", 3), ("ink", 1), ("pen", 2)] {
stock
.entry(item)
.and_modify(|count| *count += delta)
.or_insert_with(|| delta);
}
// 一次查找完成 upsert:避免 get 后再 insert 的二次哈希
let mut names: Vec<&str> = stock.keys().copied().collect();
names.sort();
for name in names {
println!("{name} -> {}", stock[name]);
}
}How the snippet works
Count the function main as the entire surface area of Entry And Modify Upserts In One Lookup.
Iteration happens inside for (item, delta) in [("pen", 3), ("ink", 1), ("pen", 2)] — everything outside it runs once.
Statements that matter
let mut names: Vec<&str> = stock.keys().copied().collect();
names.sort();
.and_modify(|count| *count += delta)
.or_insert_with(|| delta);
Interactive Tools for This Topic
FAQ
- How do you run Entry And Modify Upserts In One Lookup?
- Just run the file; everything it needs ships with the runtime itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.