Sub topic 11
Updating values with the entry API
This chapter assumes you can write basic Rust, understand moves and borrows (& and &mut), and read Option and match. It also assumes you know how to create a HashMap and call insert, get and remove. You will use the entry API to update a value in place, or create it if it is missing, with a single lookup.
The problem: check, then insert
Counting things is the standard case. For each key you want to add one to the existing count, or start at 1 if the key is new. A direct version looks the key up twice when it is absent:
use std::collections::HashMap;
fn main() {
let mut counts: HashMap<String, u32> = HashMap::new();
let word = "apple";
// Version 1: get_mut, then insert. Two lookups on a miss.
if let Some(n) = counts.get_mut(word) {
*n += 1;
} else {
counts.insert(word.to_string(), 1);
}
// Version 2: the entry API. One lookup in every case.
*counts.entry(word.to_string()).or_insert(0) += 1;
println!("{:?}", counts.get("apple")); // Some(2)
}Version 2 is shorter. It also makes it impossible to forget a branch, and it hashes the key once.
What an entry is
HashMap::entry(key) looks up the key and returns an Entry<K, V>. This is an enum with two variants:
Entry::Occupiedmeans the key is present. It holds a handle to the existing slot.Entry::Vacantmeans the key is absent. It holds the key and the position where it would go.
Methods on Entry act on whichever variant you got. They never search a second time. The chain entry(k).or_insert(v) ends by returning a &mut V that points at the value in the map.
The common methods
| Method | When the key is missing | When the key is present |
|---|---|---|
| `or_insert(v)` | Inserts `v`, returns `&mut V` | Returns `&mut V` to the old value, drops `v` |
| `or_insert_with(f)` | Calls `f()`, inserts the result | Does not call `f` |
| `or_insert_with_key(f)` | Calls `f(&key)`, inserts the result | Does not call `f` |
| `or_default()` | Inserts `V::default()` | Returns `&mut V` to the old value |
| `and_modify(f)` | Does nothing | Calls `f(&mut value)` |
and_modify returns the Entry again, so you chain it with one of the or_ methods.
Counting
Counting uses or_insert(0) and then dereferences the returned &mut u32 to add one. This is the word-count example, with a sort so the output is stable:
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 sort is needed because HashMap iteration order is unspecified and can differ between runs. Never rely on it in output you want to compare or test.
Grouping with or_default
When the value type implements Default, or_default() removes the need to name an initial value. For Vec<T> it creates an empty vector, so grouping is 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"]
}or_default() returns &mut Vec<&str>, and push is called directly on it. The same shape works for sums (u32), flags (bool) and nested maps (HashMap<_, _>).
Different logic for new and existing keys
Sometimes the first insert and later updates are not the same operation. Use and_modify followed by or_insert:
use std::collections::HashMap;
fn main() {
let mut stock: HashMap<&str, u32> = HashMap::new();
for (item, qty) in [("apple", 3), ("pear", 2), ("apple", 4)] {
stock.entry(item).and_modify(|n| *n += qty).or_insert(qty);
}
let mut items: Vec<_> = stock.into_iter().collect();
items.sort();
println!("{:?}", items); // [("apple", 7), ("pear", 2)]
}For a plain sum, *stock.entry(item).or_insert(0) += qty is equivalent and shorter. Prefer and_modify when the two cases differ, for example when a new key needs a timestamp that an update should not overwrite.
Lazy defaults with or_insert_with
The argument to or_insert is evaluated before the call, whether or not it is used. If building the default is costly, such as allocating a large buffer, pass a closure or function to or_insert_with, which runs only on a miss:
use std::collections::HashMap;
fn build_default() -> Vec<u32> {
println!("building default");
Vec::with_capacity(16)
}
fn main() {
let mut map: HashMap<&str, Vec<u32>> = HashMap::new();
map.entry("a").or_insert_with(build_default).push(1);
map.entry("a").or_insert_with(build_default).push(2);
println!("{:?}", map["a"]); // [1, 2]
}"building default" prints once. Vec::new() does not allocate, so or_insert(Vec::new()) is fine in practice. The difference matters for values like String::with_capacity(1024) or anything that reads a file or calls a service.
Matching on Entry directly
If you need to refuse a duplicate or return different results for each case, match on the enum. It lives in std::collections::hash_map:
use std::collections::hash_map::Entry;
use std::collections::HashMap;
fn register(users: &mut HashMap<String, u32>, name: &str, id: u32) -> Result<(), String> {
match users.entry(name.to_string()) {
Entry::Occupied(e) => Err(format!("{} already has id {}", name, e.get())),
Entry::Vacant(e) => {
e.insert(id);
Ok(())
}
}
}
fn main() {
let mut users = HashMap::new();
println!("{:?}", register(&mut users, "ana", 1)); // Ok(())
println!("{:?}", register(&mut users, "ana", 2)); // Err("ana already has id 1")
}OccupiedEntry also offers get_mut, into_mut, insert (which returns the old value) and remove. VacantEntry::insert returns a &mut V to the new value.
Gotchas
The returned reference keeps the map borrowed
or_insert and or_default return a &mut V tied to a mutable borrow of the whole map. While you still use that reference, you cannot call another method on the map, not even len(). This is the same rule as holding a reference into a Vec across a push. Finish with the reference first. Because borrows end at the last use, this compiles:
use std::collections::HashMap;
fn main() {
let mut map: HashMap<&str, i32> = HashMap::new();
let count = map.entry("a").or_insert(0);
*count += 1; // last use of `count`
println!("{}", map.len()); // 1
}Moving the map.len() call above *count += 1 would make the program fail to compile.
entry takes the key by value
entry needs an owned key. With a HashMap<String, _> and a &str input, entry(word.to_string()) allocates a new String on every call, even when the key already exists and the allocation is thrown away. For hot loops over mostly repeated keys, check with get_mut(word) first and call insert only on a miss, as in Version 1 at the start of this chapter. That costs two lookups on a miss but allocates only for new keys. If your keys are &str borrowed from long-lived text, as in the word-count example, entry has no such cost. The hashbrown crate also offers an entry_ref method that takes a borrowed key.
The same API exists on BTreeMap
BTreeMap::entry has the same Occupied and Vacant variants and the same or_insert family. Code that uses the entry API moves between the two map types with few changes, mainly the import path.
Exercise
What does this program print, and how many hash lookups does each loop iteration perform? let mut m: HashMap<char, u32> = HashMap::new(); for c in "banana".chars() { *m.entry(c).orinsert(0) += 1; } let mut v: Vec<> = m.into_iter().collect(); v.sort(); println!("{:?}", v);
Show answer
It prints [('a', 3), ('b', 1), ('n', 2)]. Each iteration does one lookup, because entry finds the slot once and or_insert returns a mutable reference to it. The sort makes the output deterministic, since HashMap order is unspecified.
Exercise
Write a function index_by_first_letter(words: &[&'static str]) -> HashMap<char, Vec<&'static str>> that groups words by their first character. Skip empty strings. Which entry method removes the need to write an initial empty Vec?
Show answer
Use ordefault: fn indexbyfirstletter(words: &[&'static str]) -> HashMap<char, Vec<&'static str>> { let mut index: HashMap<char, Vec<&'static str>> = HashMap::new(); for &w in words { if let Some(first) = w.chars().next() { index.entry(first).ordefault().push(w); } } index } Vec<T> implements Default, so ordefault inserts an empty Vec on first sight of a letter and returns &mut Vec to push into. The if let skips empty strings because chars().next() returns None for them.