The Analogy: The Pigeonhole Rule
A staff post room has a wall of numbered pigeonholes and one rule: apply a fixed calculation to the surname on the envelope and the answer tells you which hole it goes in. Nobody searches. Nobody keeps a list of who is in which hole. You compute, you walk to that hole, you are done -- and crucially, that walk takes the same time whether there are twelve names on the wall or twelve thousand.
The rule has to be stable and it has to agree with itself. If it produces hole 12 when you file the letter and hole 40 when you come back for it, the letter is lost -- not destroyed, just unreachable, sitting in plain sight in a hole nobody will ever compute. This is exactly why Rust demands two things of a key: Hash (the calculation) and Eq (agreement about which names count as the same name). And it is why those two must never contradict each other.
Two different surnames can of course compute to the same hole. That is fine and expected: the hole holds a small bundle and you check the names inside it. Collisions cost a little time; they break nothing. But they do mean the wall reads out in whatever order the calculation happened to produce -- nothing like alphabetical, nothing like the order the post arrived, and no promise at all that it will read out the same way tomorrow.
Finally, you have to hand the letter over. Once it is in the hole, the post room has it; you cannot both file the original and keep it in your pocket. If you need your own copy you take a photocopy first. insert moves the key and the value into the map, get lends you a look at what is in there, and the only way to keep the original as well is to clone it deliberately.
Syntax or Core Structure
HashMap<K, V> lives in std::collections, so unlike Vec and String it needs an import.
use std::collections::HashMap;
fn main() {
let mut stock: HashMap<String, u32> = HashMap::new();
stock.insert(String::from("bolts"), 120);
stock.insert(String::from("nuts"), 80);
stock.insert(String::from("washers"), 400);
let replaced = stock.insert(String::from("nuts"), 95);
println!("insert returned {:?}", replaced);
println!("bolts {:?}", stock.get("bolts"));
println!("screws {:?}", stock.get("screws"));
println!("count {}", stock.len());
println!("has nuts {}", stock.contains_key("nuts"));
let gone = stock.remove("washers");
println!("removed {:?}, now {}", gone, stock.len());
let mut rows: Vec<(&String, &u32)> = stock.iter().collect();
rows.sort();
for (name, qty) in rows {
println!(" {name} {qty}");
}
}
Output:
insert returned Some(80)
bolts Some(120)
screws None
count 3
has nuts true
removed Some(400), now 2
bolts 120
nuts 95
Three details in there are easy to skim past. insert returns the value it displaced, as an Option<V> -- Some(80) for the overwritten nuts, and None the first time a key appears. get takes a &str even though the keys are String, which works for the same borrowing reason &str parameters accept &String. And the last four lines sorted the pairs into a Vec before printing them, which is not decoration -- it is the only way to get output you can predict.
Technical Depth: Order, Entries, and the Key Contract
Iteration order is arbitrary on purpose
Rust's HashMap hashes with SipHash-1-3 seeded from a random value that the program picks at startup. That means the iteration order differs between runs of the same binary, and you should not assume two maps in one run agree either. This is not sloppiness -- it is a defence. Without a random seed, an attacker who knows your hash function can send you thousands of keys engineered to land in the same bucket, turning every lookup into a linear scan and your service into a stopped service. A random seed makes those keys unguessable.
The consequence for you is simple: if the order matters, impose one.
use std::collections::{BTreeMap, HashMap};
fn main() {
let pairs = [("north", 12), ("south", 7), ("east", 20), ("west", 3)];
let hash: HashMap<&str, u32> = pairs.into_iter().collect();
let tree: BTreeMap<&str, u32> = pairs.into_iter().collect();
let mut sorted: Vec<(&str, u32)> = hash.into_iter().collect();
sorted.sort();
print!("{:<11}", "sorted vec:");
for (k, v) in sorted {
print!(" {k}={v}");
}
println!();
print!("{:<11}", "btreemap:");
for (k, v) in &tree {
print!(" {k}={v}");
}
println!();
}
Output:
sorted vec: east=20 north=12 south=7 west=3
btreemap: east=20 north=12 south=7 west=3
Both routes give the same answer, and they cost differently. Collecting into a Vec and sorting is O(n log n) per report, which is right when you print rarely and look things up constantly. BTreeMap keeps its keys ordered at all times, paying O(log n) on every single insert and lookup, which is right when order is a standing requirement. Choosing HashMap and sorting once is usually the better trade; choosing HashMap and sorting in a loop means you wanted BTreeMap.
entry: the API that makes hash maps usable
The single most common thing you do with a map is "look at what is there and change it, inserting a starting value if nothing is there". Writing that with get and insert hashes the key twice and needs a branch. entry hashes once, finds the slot once, and hands back a &mut V.
use std::collections::HashMap;
fn main() {
let text = "the cat sat on the mat the cat was flat";
let mut counts: HashMap<&str, u32> = HashMap::new();
for word in text.split_whitespace() {
*counts.entry(word).or_insert(0) += 1;
}
println!("{} words, {} distinct", text.split_whitespace().count(), counts.len());
let mut rows: Vec<(&str, u32)> = counts.into_iter().collect();
rows.sort();
for (word, n) in rows {
println!("{n:>2} {word}");
}
}
Output:
10 words, 7 distinct
2 cat
1 flat
1 mat
1 on
1 sat
3 the
1 was
That one line, *counts.entry(word).or_insert(0) += 1, is worth reading slowly. entry(word) locates the slot for that key. or_insert(0) puts a 0 there if the slot is empty and, either way, returns a &mut u32 aimed at the value. The leading * writes through that reference. No second lookup, no reinsertion, no clone of the key unless one was actually needed.
| Call | What you get |
|---|---|
map.entry(k).or_insert(v) | &mut V, inserting v first if the key was absent |
map.entry(k).or_insert_with(f) | the same, but f() runs only on a miss |
map.entry(k).or_default() | the same, using V::default() on a miss |
map.entry(k).and_modify(f).or_insert(v) | run f on an existing value, or insert v |
map.insert(k, v) | unconditional write; returns the displaced Option<V> |
map.get(&k) | Option<&V>, and never inserts anything |
The difference between or_insert and or_insert_with is the difference between an argument and a closure, and it matters. or_insert(Vec::new()) builds a fresh Vec on every call and throws it away on every hit. or_insert_with(Vec::new) builds one only when the key is genuinely new. For a 0 that difference is nothing; for anything that allocates it is the whole cost of the loop.
Ownership at the door
insert takes the key and the value by value. Owned types move in and are gone from the caller; Copy types are copied and the original stays behind.
use std::collections::HashMap;
fn main() {
let key = String::from("region");
let value = String::from("north");
let mut map = HashMap::new();
map.insert(key, value);
// key and value have moved: neither name is usable from here on
let count = 42;
let mut copies = HashMap::new();
copies.insert(count, "answer");
println!("count is still {count}");
println!("region {:?}", map.get("region"));
println!("42 {:?}", copies.get(&42));
}
Output:
count is still 42
region Some("north")
42 Some("answer")
count survives because i32 is Copy; key and value do not, because String is not. If you need the string afterwards, map.insert(key.clone(), value) is the explicit price, and the fact that you had to type clone is the point -- the allocation is visible in the source rather than hidden in the method.
There is a matching rule on the way out. get returns Option<&V>, a borrow. get_mut returns Option<&mut V> when you want to edit in place. remove returns Option<V> -- the value itself, handed back to you, out of the map for good.
What can be a key
The bound is K: Eq + Hash, and the contract behind it is: if two keys are equal, they must hash to the same value.
| Type | Usable as a key | Why |
|---|---|---|
String, &str | yes | both traits are implemented |
integers, char, bool | yes | same |
| tuples and arrays of usable types | yes | derived component-wise |
| your own struct or enum | yes, with #[derive(Hash, PartialEq, Eq)] | the derive keeps the contract |
f64, f32 | no | NaN != NaN, so there is no Eq to have |
Vec<T> or Option<T> of a usable T | yes | derived through the contents |
Deriving all three together is what keeps the contract true. Hand-writing PartialEq to ignore a field while leaving Hash derived produces two values that are equal but land in different buckets, and the map will happily store both and find neither reliably. It is not a crash, not a warning, and not something any test written from the outside will catch.
use std::collections::HashMap;
#[derive(Hash, PartialEq, Eq)]
struct Slot {
day: u8,
hour: u8,
}
fn label(s: &Slot) -> String {
format!("day {} at {:02}:00", s.day, s.hour)
}
fn main() {
let mut rota: HashMap<Slot, &str> = HashMap::new();
rota.insert(Slot { day: 1, hour: 9 }, "ada");
rota.insert(Slot { day: 1, hour: 14 }, "ravi");
rota.insert(Slot { day: 2, hour: 9 }, "mei");
println!("{:?}", rota.get(&Slot { day: 1, hour: 14 }));
println!("{:?}", rota.get(&Slot { day: 3, hour: 9 }));
println!("{} slots filled", rota.len());
let mut keys: Vec<&Slot> = rota.keys().collect();
keys.sort_by_key(|s| (s.day, s.hour));
for s in keys {
println!("{} -> {}", label(s), rota[s]);
}
}
Output:
Some("ravi")
None
3 slots filled
day 1 at 09:00 -> ada
day 1 at 14:00 -> ravi
day 2 at 09:00 -> mei
A two-field struct as a key is often better than the string you were about to build. Slot { day: 1, hour: 9 } cannot be typoed into "1-09" versus "1-9", it allocates nothing, and sort_by_key can order it on the real fields rather than on how the digits happen to sort as text.
Real World Example: Tallying a Day of Requests
Grouping records by a key and accumulating a few numbers per group is the job hash maps were built for. Here nine request records become three per-route tallies, in one pass, with one hash lookup per record.
use std::collections::HashMap;
#[derive(Default)]
struct Tally {
hits: u32,
errors: u32,
total_ms: u32,
worst_ms: u32,
}
fn main() {
let log = [
("/health", 200, 3),
("/users", 200, 41),
("/checkout", 500, 512),
("/users", 200, 190),
("/checkout", 200, 88),
("/health", 200, 2),
("/users", 404, 12),
("/checkout", 500, 730),
("/health", 200, 4),
];
let mut by_route: HashMap<&str, Tally> = HashMap::new();
for (route, status, ms) in log {
let t = by_route.entry(route).or_default();
t.hits += 1;
t.total_ms += ms;
if status >= 400 {
t.errors += 1;
}
if ms > t.worst_ms {
t.worst_ms = ms;
}
}
let mut routes: Vec<&str> = by_route.keys().copied().collect();
routes.sort();
println!("{:<10} {:>4} {:>4} {:>5} {:>5}", "route", "hits", "err", "avg", "worst");
for route in routes {
let t = &by_route[route];
println!(
"{:<10} {:>4} {:>4} {:>5} {:>5}",
route,
t.hits,
t.errors,
t.total_ms / t.hits,
t.worst_ms
);
}
println!();
println!("{} routes, {} requests", by_route.len(), log.len());
}
Output:
route hits err avg worst
/checkout 3 2 443 730
/health 3 0 3 4
/users 3 1 81 190
3 routes, 9 requests
The whole loop body works through a single &mut Tally. by_route.entry(route).or_default() hashes the route once, finds or creates the slot, and hands back a mutable reference; the four updates that follow are plain field arithmetic with no further lookups and no reinsertion. The get-then-insert version of this loop would hash each route twice per record and would need a branch to decide which of the two paths to take -- eighteen hashes and nine branches instead of nine hashes and none.
or_default rather than or_insert(Tally::default()) is a deliberate choice. The eager form constructs a Tally on all nine iterations and discards six of them. Here that costs four zeroed integers and the optimiser almost certainly erases it, so nothing is lost either way. Change Tally to hold a Vec<u32> of every timing, though, and the eager form becomes nine allocations to keep three. or_default and or_insert_with are correct at both sizes, which is why they are worth making the habit.
The reporting half is the deterministic-order pattern in full. by_route has no order, and looping it directly would print the three routes in an arrangement that changes between runs -- excellent against hash flooding, useless for a report and impossible to write a test against. So the keys come out into a Vec, get sorted, and drive the loop while the map itself is indexed back into. keys().copied() is what keeps that cheap: the Vec holds three two-word &str values, not three copied strings, and it stops borrowing the map the moment collect finishes.
Now the limits, because this report says less than it looks like it says. total_ms / t.hits is integer division, so /checkout's real average of 443.33 prints as 443 and every average rounds down. Averages hide the shape regardless: /checkout averages 443 across requests of 88 and 730 ms, a number that describes neither of them, and the tally cannot offer a percentile because it never keeps the individual timings. status >= 400 scores a 404 exactly like a 500, lumping the client's mistakes in with yours. The &str keys borrow from log, so by_route cannot outlive the data it summarises -- fine inside one function, and precisely why a cache that lives longer than its input needs String keys and the allocation that comes with them. And nine records fit in a Vec of pairs with a linear scan more cheaply than in a hash map; the map earns its keep at a few thousand, not at nine.
Common Mistakes
- Relying on iteration order. The order is seeded randomly at startup, so it differs between runs of the same binary. Any test that asserts on printed map output, and any file format that iterates a map, is a test or a format that will fail eventually and for no visible reason. Sort, or use
BTreeMap.
- Using
map[key]for a lookup that might miss. UnlikeVec, where the index at least came from somewhere, a missing map key is the normal case.map[key]panics;map.get(key)gives youOption<&V>and a chance to react.
- Writing
gettheninsertwhereentrybelongs. It hashes the key twice, walks the buckets twice, and forces you to write the "if absent" branch by hand.entry(k).or_insert(v)is one lookup and no branch.
- Passing an expensive expression to
or_insert.or_insert(build_default())evaluatesbuild_default()on every call including every hit. Useor_insert_with(build_default)oror_default()so the work happens only on a miss.
- Forgetting that
insertmoves both arguments.map.insert(name, record)consumesnameandrecord. If you need either afterwards, clone deliberately -- and notice that you are paying for it.
- Expecting
insertto return the value you just inserted. It returns the previous value, asOption<V>, which isNonefor a brand-new key. Reading that as "did it work" gets the logic backwards.
- Forgetting the import.
HashMapis not in the prelude the wayVecandStringare. Withoutuse std::collections::HashMap;you getE0433, which reads confusingly the first time because the type obviously exists.
- Breaking the
Hash-Eqcontract, usually withf64. Floats cannot be keys at all, becauseNaNis not equal to itself and sof64has noEq. Worse is hand-writingPartialEqto ignore a field while leavingHashderived: the two now disagree, the map stores duplicates it thinks are distinct, and lookups miss values that are sitting right there.
- Holding a
&Vfromgetacross aninsert. Exactly the same reasoning asVec: an insert can trigger a resize and rehash, which moves every value. The borrow checker rejects it withE0502rather than letting you find out at runtime.
Best Practices
- Make
entrythe default for read-modify-write. One lookup, no branch, and the "insert if new" rule stated once instead of spelled out. Reach forgetonly when you genuinely just want to read.
- Prefer
or_defaultandor_insert_withoveror_insert. They are never worse and they are dramatically better the moment the value allocates. Making them the habit removes a whole class of accidental cost.
- Use
getfor lookups and[]only for keys you confirmed a line ago. The panic frommap[key]is indistinguishable from a logic bug in a stack trace; theNonefromgetnames the situation.
- Impose an order before you print, and reach for
BTreeMapif you always need one. Sorting once for a report is cheap. Sorting on every read means you chose the wrong container.
- Derive
Hash,PartialEq, andEqtogether, always. A derived trio cannot disagree. A hand-written one can, silently, in a way no test written against the public behaviour will find.
- Use a struct or tuple key instead of a formatted string.
(day, hour)cannot be typoed, cannot be ambiguous about separators, allocates nothing, and sorts on its real fields rather than on how its digits look as text.
- Match key ownership to the map's lifetime.
&strkeys are free and tie the map to the data it borrows from -- perfect inside one function. A map that outlives its input needsStringkeys, and that is a cost worth accepting rather than fighting with lifetimes.
- Do not reach for a hash map at small n. Below a few dozen entries a
Vecof pairs with a linear scan is usually faster, keeps insertion order for free, and needs noHashbound. Hashing earns its keep when the collection is large or the lookups are hot, not by default.
Practice Exercises
- Count words properly. Extend the word-count program so it folds case and strips punctuation before counting, reusing the character-filtering idea from the previous lesson. Confirm that
"The cat."and"the cat"now agree, and report both the total and the distinct count.
- Invert the map. From the request tally, build a
HashMap<u32, Vec<&str>>grouping routes by their hit count, usingentry(n).or_default().push(route). Print it in ascending count order and explain whyor_defaultmatters more here than it did in the tally.
- Swap the container. Replace
HashMapwithBTreeMapin the tally program and delete the sorting step. Confirm the output is byte-for-byte identical, then write down what you gave up and at what collection size that trade would flip back.
- Break the contract on purpose. Hand-write
PartialEqforSlotso it compares onlyday, keepHashderived, then insertSlot { day: 1, hour: 9 }andSlot { day: 1, hour: 14 }. Report whatlen()says, whatgetfinds for each, and explain from the pigeonhole rule why the map is now unable to answer correctly.