combine two maps in rust

To combine two maps, you can use the extend method or the insert method. Here is an example using extend:

main.rs
fn main() {
    let mut map1 = std::collections::HashMap::<u32, &str>::new();
    map1.insert(1, "one");
    map1.insert(2, "two");

    let mut map2 = std::collections::HashMap::<u32, &str>::new();
    map2.insert(3, "three");
    map2.insert(4, "four");

    map1.extend(map2);
    println!("{:?}", map1);
}
310 chars
13 lines

This will produce the following output:

main.rs
{1: "one", 2: "two", 3: "three", 4: "four"}
44 chars
2 lines

Alternatively, you can use the insert method to add each key-value pair from one map to the other:

main.rs
fn main() {
    let mut map1 = std::collections::HashMap::<u32, &str>::new();
    map1.insert(1, "one");
    map1.insert(2, "two");

    let mut map2 = std::collections::HashMap::<u32, &str>::new();
    map2.insert(3, "three");
    map2.insert(4, "four");

    for (key, value) in map2 {
        map1.insert(key, value);
    }

    println!("{:?}", map1);
}
358 chars
16 lines

This will produce the same output as before:

main.rs
{1: "one", 2: "two", 3: "three", 4: "four"}
44 chars
2 lines

related categories

gistlibby LogSnag