CodeBlanks Logo Icon CodeBlanks

Iterating collections

Learn iteration patterns over HashMap and Vec.

Iterating collections

Maps are iterated in three ways, each a different kind of borrow:

for (k, v) in &harita { }        // (&K, &V)
for (k, v) in &mut harita { }    // (&K, &mut V): values can be changed
for (k, v) in harita { }         // (K, V): the map is consumed

harita.keys()         // &K
harita.values()       // &V
harita.values_mut()   // &mut V

Keys are never given mutably; changing a key would break its hash.

Updating and filtering values

To apply the same operation to all values, use values_mut; to remove entries failing a condition, retain:

let mut fiyat = HashMap::from([("kalem", 5), ("defter", 12), ("silgi", 2)]);
for v in fiyat.values_mut() {
    *v *= 2;
}
fiyat.retain(|_, v| *v > 5);
let toplam: u32 = fiyat.values().sum();   // 10 + 24 = 34

HashMap::from([...]) builds a map directly from an array.

Practice Update prices

Start with HashMap::from([("kalem", 5), ("defter", 12)]). Double all prices with values_mut. Print the sorted vector of keys and the sum of the values (u32) separated by a space.

Starter code

main.rs
use std::collections::HashMap;

fn main() {
    // buraya yaz
}

Sample solution

main.rs
use std::collections::HashMap;

fn main() {
    let mut fiyat: HashMap<&str, u32> = HashMap::from([("kalem", 5), ("defter", 12)]);
    for v in fiyat.values_mut() {
        *v *= 2;
    }
    let mut anahtarlar: Vec<&str> = fiyat.keys().copied().collect();
    anahtarlar.sort();
    let toplam: u32 = fiyat.values().sum();
    println!("{:?} {}", anahtarlar, toplam);
}

Expected output

["defter", "kalem"] 34

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Can a new key be added to the map while iterating it?

  • Only in a BTreeMap
  • No; the iteration borrows the map Correct answer
  • Yes, always
  • Only in a HashMap

Explanation: Collect what to add in a separate vector first and add after the loop; or filter in place with retain.

2 Change the values

Question
for v in fiyat.____() {
    *v *= 2;
}
Answer
for v in fiyat.values_mut() {
    *v *= 2;
}

Explanation: values_mut gives &mut references to the values.

3 Method and what it gives

Term Meaning
keys() &K
values() &V
values_mut() &mut V
into_iter() (K, V)

All lessons in Intermediate