In a Rust word counter, what does `*counts.entry(word.to_string()).or_insert(0) += 1` do, and why prefer it to `contains_key` then `insert`?
answer
- one hash, one probe
- Occupied or Vacant
- or_insert returns &mut V
- entry takes the key by value
basics
~20 sentry hashes the key once and returns an Entry, Occupied or Vacant; or_insert(0) stores 0 only when vacant and returns &mut usize to the value either way, so the increment costs one lookup instead of two.
solid answer
~40 s`HashMap::entry(key)` hashes and probes once and returns `Entry::Occupied` or `Entry::Vacant`. `or_insert(0)` writes `0` only into a vacant slot and returns `&mut V` in both cases, so `*... += 1` updates in place; `contains_key` followed by `get_mut` or `insert` searches twice, and clippy's `map_entry` lint flags that pattern when the same key is checked and inserted. Related finishers: `or_insert_with` runs its closure only when vacant (an `or_insert(f())` argument is always evaluated), `or_default` uses `V::default()`, `and_modify` touches only an occupied value. The catch is that `entry` takes `K` by value, so on `HashMap<String, usize>` passing a `&str` is E0308 and `to_string()` allocates even for repeated words; when repeats dominate, `get_mut` first and `insert` only on a miss can be cheaper. Keep the returned `&mut` short-lived, or touching the map again is E0499.
code
rust · 22 linesuse std::collections::HashMap;
fn main() {
let text = "the cat and the hat and the bat";
let mut counts: HashMap<String, usize> = HashMap::new();
for word in text.split_whitespace() {
*counts.entry(word.to_string()).or_insert(0) += 1;
}
let mut by_len: HashMap<usize, Vec<&str>> = HashMap::new();
for word in text.split_whitespace() {
by_len.entry(word.len()).or_default().push(word);
}
let mut hits: HashMap<&str, u32> = HashMap::new();
for word in text.split_whitespace() {
hits.entry(word).and_modify(|n| *n += 1).or_insert(1);
}
println!("{} {} {}", counts["the"], by_len[&3].len(), hits["and"]);
}go deeper
Know the idiom for counting and grouping: entry(k).or_insert(0) and entry(k).or_default().push(x). Be able to say that or_insert leaves an existing value untouched.
Explain the Entry enum, why one probe replaces two, and the eager-argument trap of or_insert versus or_insert_with. Mention that entry needs an owned key, unlike get.
Weigh the owned-key allocation against the saved lookup on a hot, repeat-heavy counter, and show the get_mut-then-insert alternative. Diagnose the E0499 that follows from holding the returned &mut.
Accept either the entry form or the lookup-first form in review when the choice is backed by a measurement on real input. Prefer the entry form as the default, since it is shortest and clippy's map_entry lint nudges toward it.
## The counter and the two-lookup version A word-frequency counter over uploaded documents keeps a `HashMap<String, usize>` and bumps a count for each word. The first version people write checks and then acts: ```rust if counts.contains_key(word) { *counts.get_mut(word).unwrap() += 1; } else { counts.insert(word.to_string(), 1); } ``` Every word costs at least two hash-and-probe operations: one for `contains_key`, one for `get_mut` or `insert`. Clippy's **`map_entry`** lint (warn by default) flags this check-then-insert shape when the same key expression is checked and inserted, as in `if m.contains_key(&k) { ... } else { m.insert(k, v); }`; with a fresh `word.to_string()` in the `insert`, as above, clippy 1.99 stays silent, so do not count on the lint to catch it. The idiomatic one-liner is: ```rust *counts.entry(word.to_string()).or_insert(0) += 1; ``` ## What `entry` returns `HashMap::entry(&mut self, key: K) -> Entry<'_, K, V>` hashes the key **once**, probes the table **once**, and returns an **`Entry`** enum describing what it found: - `Entry::Occupied(OccupiedEntry)`: the key exists; the entry points at its slot. - `Entry::Vacant(VacantEntry)`: the key is absent; the entry already knows where it would go and holds the key you passed. The finishing method then reads or writes that slot without searching again. `or_insert(0)` writes `0` only if the entry is vacant, and in **both** cases returns **`&'a mut V`**, a mutable reference to the value now in the map. `*... += 1` increments through it. An existing count is never reset: `or_insert` does nothing to an occupied slot. ## The finishing methods | Method | When it runs its argument | Result | |---|---|---| | `or_insert(v)` | `v` is evaluated **before** the call, always | `&mut V` | | `or_insert_with(f)` | `f()` runs only if vacant | `&mut V` | | `or_insert_with_key(f)` | `f(&key)` runs only if vacant | `&mut V` | | `or_default()` | `V::default()` only if vacant | `&mut V` | | `and_modify(f)` | `f(&mut v)` only if occupied | the `Entry`, for chaining | Two patterns cover most code: 1. Counting or accumulating: `counts.entry(k).and_modify(|n| *n += 1).or_insert(1)`, or `*counts.entry(k).or_default() += 1` when the default is the starting value. 2. Grouping: `groups.entry(len).or_default().push(word)` on a `HashMap<usize, Vec<&str>>`. `or_insert(expensive())` is a classic slip: Rust evaluates arguments eagerly, so `expensive()` runs on every call, even for occupied keys. `or_insert_with(expensive)` defers it. ## The owned-key cost `entry` takes the key **by value** (`key: K`), because a vacant entry must be able to store it. On a `HashMap<String, usize>`, passing a `&str` does not compile: rustc reports **E0308** ("expected `String`, found `&str`"). `get` and `get_mut` accept a borrowed form through `Borrow`; `entry` does not. So `entry(word.to_string())` **allocates a `String` for every word**, including the many repeats where the key is already present and the new `String` is simply dropped. For a counter dominated by repeats, the allocation can cost more than the saved lookup. Two alternatives: - **Look up first, allocate only on a miss.** This compiles under non-lexical lifetimes because the `get_mut` borrow ends before `insert`: ```rust match counts.get_mut(word) { Some(n) => *n += 1, None => { counts.insert(word.to_string(), 1); } } ``` It hashes twice on a miss but allocates only for new words. - **Key the map by `&str`** borrowed from the document text, `HashMap<&str, usize>`, when the text outlives the map. Then `entry(word)` takes the `&str` directly and no per-word `String` is allocated. std's own `entry` has no borrowed-key variant; measure before preferring one form over the other. ## Borrowing rules around the returned reference The `&mut V` from `or_insert` borrows the **whole map** mutably for as long as it lives. Keeping it in a variable and calling `counts.insert(...)` before its last use is rejected with **E0499** ("cannot borrow `counts` as mutable more than once at a time"). Use the reference immediately, as the `*... += 1` form does, and the borrow ends at the end of the statement. How E0499 and its fixes work in general is covered with borrow-checker errors. ## Checklist - One lookup: `entry(k)` plus a finishing method. - Lazy defaults: `or_insert_with` or `or_default`, never `or_insert(costly())`. - Owned key: expect an allocation per call on `String` keys, and weigh it against the lookup saved. - Short-lived `&mut`: finish with the value before touching the map again.
- When is `or_insert_with` the right call rather than `or_insert`?Whenever building the default costs something. Arguments are evaluated before the call, so `or_insert(Vec::with_capacity(64))` or `or_insert(load_from_disk())` does the work for every key, occupied or not. `or_insert_with(|| ...)` runs the closure only for a vacant entry. `or_default()` is the short form when `V::default()` is the value you want.
- Why does `counts.entry(word)` fail when `word` is a `&str` and the map is `HashMap<String, usize>`?`entry` takes `key: K` by value because a vacant entry has to store it, so the argument must be a `String`; rustc reports E0308, expected `String`, found `&str`. `get` and `get_mut` accept borrowed forms through `Borrow`, `entry` does not. Pass `word.to_string()`, look up with `get_mut` before allocating, or key the map by `&str` when the text outlives it.
- How do you build a default from the key itself, say the word's length, without cloning the key first?Use `or_insert_with_key`, whose closure receives `&K` only when the entry is vacant: `lens.entry(word.to_string()).or_insert_with_key(|k| k.len())`. The key has already moved into the entry, so the closure borrows it from there instead of needing a second copy.
- entry searches the map twice, once to check and once to insert
- or_insert resets an existing value to the default
- counts.entry(word) accepts a &str on HashMap<String, usize> as get does
- or_insert(expensive()) calls expensive() only when the key is missing
- The &mut from or_insert can be held while inserting other keys