Sub topic 12
Iterating over keys, values and pairs
This chapter assumes you can create a HashMap, insert and read entries, and that you know how for loops borrow or consume a collection. If those are new, review the earlier chapters on Vec iteration and HashMap basics first.
Three ways to walk a map
A HashMap<K, V> has no index. You iterate it with one of three views: pairs, keys, or values. Each view has a shared and a mutable form.
| Method | Item type | Use it to |
|---|---|---|
| `iter()` or `&map` | `(&K, &V)` | Read keys and values |
| `iter_mut()` or `&mut map` | `(&K, &mut V)` | Change values in place |
| `keys()` | `&K` | Read keys only |
| `values()` | `&V` | Read values only |
| `values_mut()` | `&mut V` | Change values only |
| `into_iter()` or `map` | `(K, V)` | Consume the map and take ownership |
Keys are never handed out mutably. Changing a key could change its hash and leave the entry in the wrong bucket.
Reading pairs, keys and values
use std::collections::HashMap;
fn main() {
let mut stock: HashMap<String, u32> = HashMap::new();
stock.insert(String::from("apple"), 3);
stock.insert(String::from("pear"), 0);
stock.insert(String::from("plum"), 8);
for (name, count) in &stock {
println!("{name}: {count}");
}
let total: u32 = stock.values().sum();
println!("total = {total}");
let mut names: Vec<&String> = stock.keys().collect();
names.sort();
println!("{:?}", names); // ["apple", "pear", "plum"]
}Iterating &stock borrows the map, so you can use stock again afterward. The for pattern (name, count) destructures each pair, and both bindings are references.
Order is not guaranteed
A HashMap yields entries in an arbitrary order. The order can differ between runs and between maps with the same contents. Never rely on it, and never print a map in a test and compare against fixed text.
If you need a stable order, collect the keys into a Vec and sort it, as above. If you need sorted order all the time, a BTreeMap is the better fit, and a later chapter compares the two.
Changing values while iterating
Use iter_mut or values_mut and dereference the value reference with *.
use std::collections::HashMap;
fn main() {
let mut prices: HashMap<&str, f64> = HashMap::new();
prices.insert("tea", 2.0);
prices.insert("coffee", 3.5);
for price in prices.values_mut() {
*price *= 1.1;
}
for (item, price) in prices.iter_mut() {
if *item == "tea" {
*price += 0.5;
}
}
let mut items: Vec<_> = prices.iter().collect();
items.sort_by(|a, b| a.0.cmp(b.0));
for (item, price) in items {
println!("{item}: {price:.2}");
}
}This prints coffee: 3.85 and tea: 2.70.
Common errors
- Adding or removing entries inside the loop. The loop borrows the map, so calling
insertorremoveon it fails with a borrow error. Collect the keys first, or useretainto drop entries in one pass. - Using the map after
for x in map. Iterating by value moves the map. Iterate&mapif you still need it. - Expecting
(K, V)fromiter(). You get references. Compare with*item == "tea"oritem == &"tea", and dereference values before doing arithmetic.
use std::collections::HashMap;
fn main() {
let mut scores: HashMap<&str, i32> = HashMap::from([("a", 5), ("b", 0), ("c", 9)]);
scores.retain(|_, score| *score > 0);
let mut keys: Vec<_> = scores.keys().collect();
keys.sort();
println!("{:?}", keys); // ["a", "c"]
}Exercise
You have let mut m: HashMap<String, i32>. Write a loop that doubles every value, then explain why for (k, v) in &m { *v *= 2; } does not compile.
Show answer
Use for v in m.values_mut() { *v *= 2; } or for (_, v) in m.iter_mut() { *v *= 2; }. Iterating &m yields (&String, &i32), which are shared references, so assigning through v is not allowed. Mutation needs &mut m or iter_mut, which yields &mut i32.