Collections: Vec, HashMap & More
The standard collections and when to use each one.
The standard library provides the collections most programs need: Vec for sequences, HashMap and BTreeMap for key-value lookups, HashSet for unique values and VecDeque for queues and ring buffers.
The collections in action
sort_by with partial_cmp is needed for floats, because NaN has no defined order.
get(10) returns None instead of panicking like temps[10] would.
entry(word).or_insert(0) inserts a zero the first time a word is seen, then increments it.
HashMap has no defined iteration order, so the counts are sorted before printing; BTreeMap is always sorted by key (0x101 = 257, 0x150 = 336, 0x200 = 512).
The VecDeque keeps the last three samples, like a fixed-size window.
Choosing
for i in 0..v.len() { total += v[i]; } for x in &v { total += x; } // or v.iter().sum()
Index loops are noisier and re-check bounds on every access. Iterators are clearer and at least as fast.
When would you use BTreeMap instead of HashMap?
When you need the keys in sorted order (ordered iteration, range queries, deterministic output) or keys that can be ordered but not hashed.