How to use iter_mut() to modify hashmap without loop?

Viewed 29

I have a hashmap: [("a", 1), ("b", 2), ("c", 3)], now I want to use iter_mut() method to double each of the value. However, the example uses a loop. Like this: for (_, val) in map.iter_mut() { *val *= 2; } how can I do the same thing without the for loop?

1 Answers
use std::collections::HashMap;

fn main() {
    let mut map = HashMap::from([("a", 1), ("b", 2), ("c", 3)]);

    map.iter_mut().for_each(|(_, val)| {
        *val *= 2;
    });

    println!("{:?}", map);
}
{"c": 6, "a": 2, "b": 4}
Related