我如何创建一个HashMap文字

我如何创建一个HashMap文字

本文介绍了我如何创建一个HashMap文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在Rust中创建一个HashMap文字?在Python中,我可以这么做:

  hashmap = {
'element0':{
'name ':'我的新元素',
'childs':{
'child0':{
'name':'Child For Element 0',
'childs':{
...
}
}
}
},
...
}



  type节点结构{
名称字符串
childs map [字符串]节点
}

hashmap:= map [string]节点{
element0:Node {
My New Element,
map [string]节点{
'child0':节点{
Child For Element 0,
map [string] Node {}
}
}
}
}


解决方案

Rust中没有地图文字语法。我不知道确切原因,但是我期望有多个数据结构可以像map一样操作(比如和)将会使得很难选择一个。 / p>

但是,您可以创建一个宏为您完成这项工作,如。这是宏简化了一点,并有足够的结构,以使它:

  macro_rules! map(
{$($ key:expr => $ value:expr),+} => {
{
let mut m = :: std :: collections :: HashMap :: new();
$(
m.insert($ key,$ value);
)+
m
}
};
);

fn main(){
let names = map!{1 => one,2 => two};
println!({} - > {:?},1,names.get(& 1));
println!({} - > {:?},10,names.get(& 10));
}


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

hashmap = {
   'element0': {
       'name': 'My New Element',
       'childs': {
           'child0': {
               'name': 'Child For Element 0',
               'childs': {
                   ...
               }
           }
       }
   },
   ...
}

And in Go like this:

type Node struct {
    name string
    childs map[string]Node
}

hashmap := map[string]Node {
    "element0": Node{
        "My New Element",
        map[string]Node {
            'child0': Node{
                "Child For Element 0",
                map[string]Node {}
            }
        }
    }
}
解决方案

There isn't a map literal syntax in Rust. I don't know the exact reason, but I expect that the fact that there are multiple data structures that act maplike (such as both BTreeMap and HashMap) would make it hard to pick one.

However, you can create a macro to do the job for you, as demonstrated in Why does this rust HashMap macro no longer work?. Here is that macro simplified a bit and with enough structure to make it runnable in the playground:

macro_rules! map(
    { $($key:expr => $value:expr),+ } => {
        {
            let mut m = ::std::collections::HashMap::new();
            $(
                m.insert($key, $value);
            )+
            m
        }
     };
);

fn main() {
    let names = map!{ 1 => "one", 2 => "two" };
    println!("{} -> {:?}", 1, names.get(&1));
    println!("{} -> {:?}", 10, names.get(&10));
}

这篇关于我如何创建一个HashMap文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 15:27