How do I create a HashMap literal?

后端 未结 6 1481
再見小時候
再見小時候 2020-11-29 21:11

How I can create a HashMap literal in Rust? In Python I can do it so:

hashmap = {
   \'element0\': {
       \'name\': \'My New Element\',
       \'childs\':          


        
6条回答
  •  执念已碎
    2020-11-29 21:33

    For one element

    If you wish to initialize the map with only one element in one line (and without visible mutation in your code), you could do:

    let map: HashMap<&'static str, u32> = Some(("answer", 42)).into_iter().collect();
    

    This is thanks to the usefulness of Option being able to become an Iterator using into_iter().

    In real code, you probably don't need to help the compiler with the type:

    use std::collections::HashMap;
    
    fn john_wick() -> HashMap<&'static str, u32> {
        Some(("answer", 42)).into_iter().collect()
    }
    
    fn main() {
        let result = john_wick();
    
        let mut expected = HashMap::new();
        expected.insert("answer", 42);
    
        assert_eq!(result, expected);
    }
    

    There is also a way to chain this to have more than one element doing something like Some(a).into_iter().chain(Some(b).into_iter()).collect(), but this is longer, less readable and probably has some optimization issues, so I advise against it.

提交回复
热议问题