How do I create a map from a list in a functional way?

后端 未结 2 1400
后悔当初
后悔当初 2020-12-06 04:01

In Scala, there is a method named toMap that works on any list of tuples and converts it to a map where the key is the first item on the tuple and the value is

2条回答
  •  被撕碎了的回忆
    2020-12-06 04:26

    Since it wasnt already mentioned, here is a single line (albeit long) method:

    use std::collections::HashMap;
    
    fn main() {
       let m: HashMap<&str, u16> = [("year", 2019), ("month", 12)].iter().cloned().collect();
       println!("{:?}", m);
    }
    

    Or you can do a Trait:

    use std::collections::HashMap;
    
    trait Hash {
       fn to_map(&self) -> HashMap<&str, u16>;
    }
    
    impl Hash for [(&str, u16)] {
       fn to_map(&self) -> HashMap<&str, u16> {
          self.iter().cloned().collect()
       }
    }
    
    fn main() {
       let m = [("year", 2019), ("month", 12)].to_map();
       println!("{:?}", m)
    }
    

    https://doc.rust-lang.org/std/collections/struct.HashMap.html#examples

提交回复
热议问题