How do I create a HashMap literal?

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

    I recommend the maplit crate.

    To quote from the documentation:

    Macros for container literals with specific type.

    use maplit::hashmap;
    
    let map = hashmap!{
        "a" => 1,
        "b" => 2,
    };
    

    The maplit crate uses => syntax for the mapping macros. It is not possible to use : as separator due to syntactic the restrictions in regular macro_rules! macros.

    Note that rust macros are flexible in which brackets you use for the invocation. You can use them as hashmap!{} or hashmap![] or hashmap!(). This crate suggests {} as the convention for the map & set macros, it matches their Debug output.

    Macros

    • btreemap Create a BTreeMap from a list of key-value pairs
    • btreeset Create a BTreeSet from a list of elements.
    • hashmap Create a HashMap from a list of key-value pairs
    • hashset Create a HashSet from a list of elements.

提交回复
热议问题