166. Entry::and_modify — Update If Present, Insert If Not, in One Chain
*map.entry(k).or_insert(0) += 1 is the classic Rust counter. The moment the “first time” branch needs to look different from the “next time” branch, that pattern stops fitting — and and_modify slots in.
HashMap::entry(k) returns an Entry enum pointing at the slot for k, occupied or vacant. The famous methods are or_insert(default) and or_insert_with(|| ...). Quieter but often nicer is and_modify: it runs a closure on the value when the key is already there, and does nothing when it isn’t. Chain it with or_insert and you get update if present, insert if not in one expression — with a single lookup.
| |
For pure counters that’s a tie with *entry.or_insert(0) += 1. The shape really pays off when the two branches store different data. Imagine grouping events by user, where the first event records the user’s name and later events only bump a counter:
| |
and_modify takes &mut V so you mutate in place; or_insert produces the initial V. and_modify also returns the Entry back, which is why the chain works — and which means you can stack several modifications before the final or_insert.