Want to insert a value into a HashMap only if the key doesn’t exist yet? Skip the double lookup — use the entry API.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| use std::collections::HashMap;
let mut scores: HashMap<&str, Vec<u32>> = HashMap::new();
// Instead of checking .contains_key() then inserting:
scores.entry("alice")
.or_insert_with(Vec::new)
.push(100);
scores.entry("alice")
.or_insert_with(Vec::new)
.push(200);
assert_eq!(scores["alice"], vec![100, 200]);
|
The entry API returns an Entry enum — either Occupied or Vacant. The convenience methods make common patterns a one-liner:
1
2
3
4
5
6
7
8
9
10
| use std::collections::HashMap;
let mut word_count: HashMap<&str, usize> = HashMap::new();
let words = ["hello", "world", "hello", "rust", "hello"];
for word in words {
*word_count.entry(word).or_insert(0) += 1;
}
// hello => 3, world => 1, rust => 1
|
or_insert(val) inserts a default, or_insert_with(|| val) lazily computes it, and or_default() uses the type’s Default. All three return a mutable reference to the value, so you can update in place.