How to Merge Two HashMaps in Rust

Merge two Rust HashMaps by iterating over the second map and inserting its entries into the first using the Entry API.

You merge two HashMaps by iterating over the second map and inserting its key-value pairs into the first, using entry().or_insert() to handle collisions.

use std::collections::HashMap;

let mut map1: HashMap<&str, i32> = HashMap::from([("a", 1), ("b", 2)]);
let map2: HashMap<&str, i32> = HashMap::from([("b", 3), ("c", 4)]);

for (k, v) in map2 {
    map1.entry(k).or_insert(v);
}

// map1 now contains: {"a": 1, "b": 2, "c": 4}

Note: This keeps the original value from map1 if keys collide. To overwrite with map2's value, use map1.insert(k, v); instead.