Using HashMaps
Imagine you have a notebook where you write down your friends' names and their favorite colors. You look up a name, and you find their color right next to it. That's exactly what a HashMap does in Rust! It stores keys (like names) paired with values (like colors).
Importing HashMap
Unlike vectors, HashMaps aren't included automatically. You need to tell Rust you want to use them:
The use std::collections::HashMap; line goes at the very top of your file. After that, you can create HashMaps with HashMap::new() and add entries with .insert(key, value).
Looking Up Values with .get()
To find a value by its key, use .get(). It returns an Option because the key might not exist:
The .get() method returns Some(value) if the key exists, or None if it doesn't. Using if let Some(...) is a safe way to handle both cases.
Checking if a Key Exists
Want to know if a key is in the HashMap without getting its value? Use .contains_key():
Removing Items and Checking Length
Use .remove() to delete a key-value pair, and .len() to see how many entries are in the map:
Iterating Over a HashMap
You can loop through all the key-value pairs using a for loop. Use & to borrow the map so you can still use it afterward:
Important: HashMaps don't store items in any particular order! If you need items in a specific order, you can collect the keys into a vector and sort it first.
Updating Values
If you .insert() a key that already exists, the old value gets replaced:
You can also use the entry() API to only insert if the key doesn't exist yet, or to modify the existing value:
The entry().or_insert(0) pattern is super handy for counting things. It gives you a reference to the value, which you can then update with *count += 1.
Summary
| Concept | What it does |
|---|---|
use std::collections::HashMap | Imports HashMap |
HashMap::new() | Creates an empty HashMap |
.insert(key, value) | Adds or updates an entry |
.get(key) | Returns Some(value) or None |
.contains_key(key) | Checks if a key exists |
.remove(key) | Removes an entry |
.len() | Returns how many entries are in the map |
for (k, v) in &map | Loops through all entries |
.entry(key).or_insert(val) | Insert only if key is missing |
Now let's practice using HashMaps!