`HashMap`
HashMap<K, V> is a hash table from keys to values. Average lookup, insert, and remove are O(1). Keys must implement Eq and Hash.
Detailed Explanation
HashMap stores key-value pairs in a flat table (SwissTable / hashbrown in current std). A hash of the key picks a slot; collisions are resolved in the table, not in a linked list you manage. insert overwrites an existing key and returns the old value. get returns Option<&V>. entry is the API for "insert if missing": map.entry(key).or_insert(default) hashes once.
Keys are hashed and compared. K: Eq + Hash is required. If two keys compare equal they must hash equal, or the map will lose entries. Do not implement Hash by hand unless you also control Eq. Floats are a poor key because NaN != NaN. Prefer String, integers, or a newtype.
The default hasher is SipHash-1-3 (or the current std equivalent), chosen to resist HashDoS: an attacker who can pick keys should not be able to force every insert into one bucket and turn your O(1) into O(n). For trusted inner loops, the hashbrown crate or a BuildHasher such as ahash / rustc-hash is faster and weaker against that attack. Measure before you switch.
HashMap does not keep insertion order. Iteration order is random-looking and may change between runs (Rust randomises the seed). If you need order, use BTreeMap, keep a Vec of keys, or use the indexmap crate. HashMap is not sorted. HashMap is not thread-safe; wrap it in Mutex or use a concurrent crate.
or_insert takes a ready-made value and constructs it even when the key exists if you write or_insert(expensive()). Use or_insert_with(|| expensive()) so the closure runs only on a miss.
When you reach for HashMap: lookups by an unordered key. When you reach for BTreeMap: you need sorted keys, ranges, or a deterministic order. When you reach for Vec<(K, V)>: n is tiny and you will scan.
Code Examples
use std::collections::HashMap;
fn main() {
let mut hits: HashMap<&str, u32> = HashMap::new();
*hits.entry("ada").or_insert(0) += 1;
*hits.entry("ada").or_insert(0) += 1;
println!("{}", hits.get("ada").unwrap()); // prints: 2
println!("{:?}", hits.get("missing")); // prints: None
}Common Gotchas
`get` returns `Option`
`map["k"]` panics when the key is missing. Use `get` or `entry`.
`or_insert(expensive())` always builds `expensive()`
Use `or_insert_with` so the work runs only on a vacant entry.
Iteration order is not insertion order
Tests that snapshot `format!("{:?}", map)` will flake. Sort the keys, or use `BTreeMap`.
Custom `Hash` must agree with `Eq`
A derived `Hash` plus a handwritten `Eq` that ignores a field is a bug. Derive both or neither.