How do I create a HashMap literal?

后端 未结 6 1480
再見小時候
再見小時候 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:27

    As noted by @Johannes in the comments, it's possible to use vec![] because:

    • Vec implements the IntoIterator trait
    • HashMap implements FromIterator

    which means you can do this:

    let map: HashMap = vec![("key".to_string(), "value".to_string())]
        .into_iter()
        .collect();
    

    You can use &str but you might need to annotate lifetimes if it's not 'static:

    let map: HashMap<&str, usize> = vec![("one", 1), ("two", 2)].into_iter().collect();
    

提交回复
热议问题