find the intersection of two maps in rust

To find the intersection of two maps (HashMaps) in Rust, we can iterate over one map and check if the key exists in the other map.

Here's an example implementation:

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

fn main() {
    let map1: HashMap<i32, &str> = [(1, "one"), (2, "two"), (3, "three"), (4, "four")].iter().cloned().collect();
    let map2: HashMap<i32, &str> = [(3, "three"), (4, "four"), (5, "five")].iter().cloned().collect();
    
    let intersection: HashMap<&i32, &&str> = map1.iter().filter(|(key, _)| map2.contains_key(key)).collect();
    
    println!("{:?}", intersection); // Output: {3: "three", 4: "four"}
}
454 chars
11 lines

In the code above, we first create two HashMap instances map1 and map2. We then make use of the filter() function to only collect the key-value pairs where the key exists in both maps. Finally, we create a new HashMap from the filtered iterator.

The intersection variable will be of type HashMap<&i32, &&str>, which is a HashMap with the keys being references to the keys of map1, and the values being references to the values of map2 (since we used a double reference).

gistlibby LogSnag