Rust Tutorial: HashMap
Store key-value pairs with HashMap. Insert, lookup, update, and iterate.
Key-value lookup
`HashMap<K, V>` stores key-value pairs with O(1) average lookup. It is the go-to collection for mapping names to values.
What you'll learn in this Rust hashmap tutorial
This interactive Rust tutorial has 8 hands-on exercises. Estimated time: 18 minutes.
- Create a HashMap — Import `HashMap` from `std::collections`. Use `insert` to add entries.
- Iterate a HashMap — Iterating gives (key, value) pairs. Order is not guaranteed.
- contains_key and remove — Check existence with `contains_key`. Remove with `remove`.
- entry API — The `entry` API updates a value or inserts a default elegantly:
- HashMap from iterator — Build a HashMap from an iterator of (key, value) pairs using `.collect()`.
- Counting with HashMap — A common pattern: count frequencies.
- Nested HashMap — HashMap values can be any type, including other HashMaps.
- HashMap vs Vec — when to use which — Use Vec when order matters or data is indexed by position.
Rust HashMap concepts covered
- Key-value lookup