Merge two HashMaps in Rust

后端 未结 2 592
无人共我
无人共我 2021-01-02 00:30

So I\'m a bit stuck, trying to merge two HashMaps.

It\'s easy to do it inline:

fn inline() {
    let mut first_context = HashMap::new();
    first_co         


        
2条回答
  •  太阳男子
    2021-01-02 00:57

    A more up to date answer from this tweet:

    use std::collections::HashMap;
    
    // Mutating one map
    fn merge1(map1: &mut HashMap<(), ()>, map2: HashMap<(), ()>) {
        map1.extend(map2);
    }
    
    // Without mutation
    fn merge2(map1: HashMap<(), ()>, map2: HashMap<(), ()>) -> HashMap<(), ()> {
        map1.into_iter().chain(map2).collect()
    }
    
    // If you only have a reference to the map to be merged in
    fn merge_from_ref(map: &mut HashMap<(), ()>, map_ref: &HashMap<(), ()>) {
        map.extend(map_ref.into_iter().map(|(k, v)| (k.clone(), v.clone())));
    }
    

    Rust Playground Link

提交回复
热议问题