HashMaps
8 min · Rust
Look up values by key with HashMap — Rust's dictionary.
Enemy 1 of 5
A Vec is great when order matters and you look things up by position. But often you want to look something up by a meaningful name instead — a player's username, a product's SKU, a word you're counting. That's what a HashMap<K, V> is for: it stores key-value pairs, where K is the type of the keys and V is the type of the values, and lets you retrieve a value almost instantly given its key, no matter how many pairs are stored.
Unlike Vec, vec!, and String, HashMap isn't automatically available — it lives in Rust's standard collections module, so you need to bring it into scope with use std::collections::HashMap; at the top of the file before you can use it. This is a common pattern in Rust: the most frequently used types (like Vec and String) are always available, while more specialized ones need an explicit use statement.
.insert(key, value) stores a pair, and .get(&key) retrieves one, wrapped in a special type called Option that represents either "a value was found" (Some(value)) or "nothing was found" (None). .unwrap() is a quick way to say "I'm confident this key exists, just give me the value or crash if I'm wrong" — it's fine for learning and small scripts, but in production code you'd usually handle the None case gracefully instead of unwrapping blindly, since an unexpectedly missing key would otherwise crash the whole program.
Loading editor...