HashMap Entry API With Or Insert
Count events with the HashMap entry API so insertion and mutation share one lookup, using or_insert for scalars and or_default for lists.
Code
use std::collections::HashMap;
fn main() {
let events = ["login", "view", "login", "cart", "view", "login"];
// entry API:不存在就插入 0,再原地累加,避免二次查找
let mut counts: HashMap<&str, u32> = HashMap::new();
for event in events {
*counts.entry(event).or_insert(0) += 1;
}
println!("login count: {}", counts["login"]);
println!("contains cart: {}", counts.contains_key("cart"));
// or_default 首次出现时初始化 Vec:分组收集的惯用写法
let mut by_first: HashMap<char, Vec<&str>> = HashMap::new();
for event in events {
by_first
.entry(event.chars().next().unwrap())
.or_default()
.push(event);
}
println!("keys starting 'l': {:?}", by_first[&'l']);
// HashMap 遍历无序:排序键后输出才稳定
let mut names: Vec<&str> = counts.keys().copied().collect();
names.sort_unstable();
for name in names {
println!("{}: {}", name, counts[name]);
}
}How the snippet works
HashMap Entry API With Or Insert keeps everything in the function main.
Iteration happens inside for event in events — everything outside it runs once.
Applying it
Look for the login count:, contains cart:, keys starting 'l': prefixes when the file runs; they tie each line to its step.
Statements that matter
let mut names: Vec<&str> = counts.keys().copied().collect();
.entry(event.chars().next().unwrap())
.or_default()
.push(event);
Interactive Tools for This Topic
FAQ
- What does HashMap Entry API With Or Insert print when run?
- Run it as a complete program — the output lines carry labels such as `login count:`, `contains cart:`, `keys starting 'l':`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.