Sub topic 11
Updating values with the entry API
This chapter assumes you can create a HashMap, call insert and get, and read Option values with match. It also assumes you know what &mut means.
The problem: check, then insert
Suppose you want to count words. A direct approach looks up the key twice.
use std::collections::HashMap;
fn main() {
let mut counts: HashMap<&str, usize> = HashMap::new();
for word in ["a", "b", "a"] {
if counts.contains_key(word) {
*counts.get_mut(word).unwrap() += 1;
} else {
counts.insert(word, 1);
}
}
println!("{:?}", counts.get("a")); // Some(2)
}This works, but it hashes the key two or three times per word and needs an unwrap. The entry API does the same job with one lookup.
How entry works
map.entry(key) looks the key up once and returns an Entry. The Entry is either occupied or vacant. You then say what to do in each case.
Counting with or_insert
or_insert returns a &mut V in both cases. You change the value by dereferencing it with *.
use std::collections::HashMap;
fn main() {
let text = "the quick brown fox jumps over the lazy dog the end";
let mut counts: HashMap<&str, usize> = HashMap::new();
for word in text.split_whitespace() {
*counts.entry(word).or_insert(0) += 1;
}
let mut pairs: Vec<_> = counts.iter().collect();
pairs.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));
for (word, count) in pairs.iter().take(3) {
println!("{word}: {count}");
}
// the: 3
// brown: 1
// dog: 1
}The program sorts the pairs before printing because HashMap iteration order is unspecified.
Grouping with or_default
or_default inserts V::default() when the key is missing. For a Vec, that is an empty vector, so grouping takes one expression.
use std::collections::HashMap;
fn main() {
let mut groups: HashMap<usize, Vec<&str>> = HashMap::new();
for word in ["cat", "dog", "bird", "fish", "ox"] {
groups.entry(word.len()).or_default().push(word);
}
println!("{:?}", groups[&3]); // ["cat", "dog"]
println!("{:?}", groups[&4]); // ["bird", "fish"]
}Choosing a method
| Method | Use it when |
|---|---|
| `or_insert(v)` | The default is cheap to build. |
| `or_insert_with(f)` | The default is costly, so `f` should run only for missing keys. |
| `or_default()` | The value type implements `Default`. |
| `and_modify(f).or_insert(v)` | You need different behavior for existing and new keys. |
or_insert(v) builds v every time, even when the key exists. For a value like Vec::with_capacity(1000), use or_insert_with instead.
Common errors
- Forgetting the dereference.
counts.entry(word).or_insert(0) += 1does not compile, because the left side is a&mut usize. Write*counts.entry(word).or_insert(0) += 1. - Holding the reference too long. The returned
&mut Vborrows the whole map. You cannot callcounts.len()or insert another key while you still use that reference. Finish with it first. - Moving the key.
entrytakes the key by value. For aStringkey, the string moves into the map if the key is vacant. Clone it first if you need it afterward.
Exercise
Write a loop that builds a HashMap<char, u32> counting how often each character appears in "hello". What is the count for 'l'?
Show answer
for c in "hello".chars() { *counts.entry(c).or_insert(0) += 1; } gives 'l' a count of 2. 'h', 'e' and 'o' each have 1.