如何将Vec <string>扩展为HashMap值?

时间:2017-07-05 14:38:33

标签: vector hashmap rust

我有start /?。我无法弄清楚如何通过增长HashMap<String, Vec<String>>来更新价值。我认为以下内容可行:

Vec

但它反而给出错误

fn add_employee(mut data: HashMap<String, Vec<String>>) -> HashMap<String, Vec<String>> {
    loop {
        println!("Please enter the name of the employee you would like to manage.");

        let mut employee = String::new();

        io::stdin().read_line(&mut employee).expect(
            "Failed to read line",
        );

        let employee = employee.trim();

        let mut department = String::new();

        println!("Please enter the name of the department you would like to add the employee to.");

        io::stdin().read_line(&mut department).expect(
            "Failed to read line",
        );

        let department = department.trim();

        data.entry(department.to_string())
            .extend(vec![employee.to_string()])
            .or_insert(vec![employee.to_string()]);
    }
}

2 个答案:

答案 0 :(得分:2)

在考虑了入口API之后,我想出了以下解决方案:

string userName = "userName";
String orderStr = $@"{{
      ""currency"":""MXN"",
      ""customer_info"": {{
        ""name"": ""julio"",
        ""phone"": ""Cabalos"",
        ""email"": ""el@el.com""
      }},
      ""line_items"": [{{
        ""name"": ""\'{userName}\'"",
        ""description"": ""descripc"",
        ""unit_price"": 233,
        ""quantity"": '1',
        ""tags"": [""Transporte"", ""Logistic Cloud""],
        ""type"": ""physical""
      }}],
     ""charges"":[{{
        ""payment_method"": {{
          ""type"": ""oxxo_cash""
        }}
      }}]
   }}";

答案 1 :(得分:1)

使用此代码:

use std::collections::hash_map::Entry;

match data.entry(department.to_string()) {
    Entry::Occupied(mut entry)  => { entry.get_mut().push(employee.to_string()); },
    Entry::Vacant(entry)        => { entry.insert(vec!(employee.to_string())); },
}
  • 如果密钥存在,请获取值的可变引用并添加新字符串
  • 否则,创建一个新的向量并将其插入到hashmap中。

所有这些信息都在documentation