find the union of two maps in rust

To find the union of two maps in Rust, you can use the extend method and the iter method. The extend method can be used to insert all key-value pairs from one map into another map. The iter method is used to obtain an iterator over the key-value pairs of the second map, which can then be passed to the extend method.

Here's an example code snippet:

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

fn main() {
    let mut map1 = HashMap::new();
    map1.insert("a", 1);
    map1.insert("b", 2);
    map1.insert("c", 3);

    let mut map2 = HashMap::new();
    map2.insert("b", 20);
    map2.insert("d", 40);

    map1.extend(map2.into_iter());
    println!("{:?}", map1); // {"a": 1, "b": 20, "c": 3, "d": 40}
}
346 chars
16 lines

In this example, we have two maps map1 and map2. We insert a few key-value pairs in each of them. Then, using the extend method, we insert all the key-value pairs from map2 into map1. Finally, we print the resulting map1 map containing the union of the two maps.

related categories

gistlibby LogSnag