How to borrow from HashMap while iterating

Collect keys into a vector before iterating to safely mutate HashMap values.

You cannot borrow a value mutably from a HashMap while iterating over it because the iterator holds an immutable borrow of the map, preventing any mutable access. Instead, collect the keys you need to modify into a Vec first, then iterate over that list to update the map.

use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();
    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);

    let keys_to_update: Vec<_> = scores.keys().cloned().collect();
    for key in keys_to_update {
        if let Some(entry) = scores.get_mut(&key) {
            *entry += 1;
        }
    }
}