如何在将字符串与字符串向量配对的哈希映射的值中添加元素? [英] How do I add an element to the value of a hash map that pairs strings with vectors of strings?

查看:107
本文介绍了如何在将字符串与字符串向量配对的哈希映射的值中添加元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像许多新的Rustaceans一样,我一直在研究锈皮书.我正在阅读有关收藏的一章,并且被困在其中一项练习.内容为:

Like many new Rustaceans, I've been working my way through the Rust Book. I'm reading through the chapter on collections, and I'm stuck on one of the exercises. It reads:

使用哈希图和向量,创建一个文本界面,以允许用户将员工姓名添加到公司的部门中.例如,将Sally添加到工程中"或将Amir添加到销售中".然后让用户检索部门中所有人员或部门中公司所有人员的列表,并按字母顺序排序.

Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in a company. For example, "Add Sally to Engineering" or "Add Amir to Sales." Then let the user retrieve a list of all people in a department or all people in the company by department, sorted alphabetically.

到目前为止,这是我的代码:

Here is my code so far:

use std::collections::hash_map::OccupiedEntry;
use std::collections::hash_map::VacantEntry;
use std::collections::HashMap;
use std::io;

fn main() {
    println!("Welcome to the employee database text interface.\nHow can I help you?");

    let mut command = String::new();

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

    command = command.to_lowercase();

    let commands = command.split_whitespace().collect::<Vec<&str>>();

    let mut department = commands[3];
    let mut name = commands[1];

    let mut employees = HashMap::new();

    if commands[0] == "add" {
        match employees.entry(department) {
            VacantEntry(entry) => entry.entry(department).or_insert(vec![name]),
            OccupiedEntry(entry) => entry.get_mut().push(name),
        }
    }
}

编译器返回以下错误:

error[E0532]: expected tuple struct/variant, found struct `VacantEntry`
  --> src/main.rs:26:13
   |
26 |             VacantEntry(entry) => entry.entry(department).or_insert(vec![name]),
   |             ^^^^^^^^^^^ did you mean `VacantEntry { /* fields */ }`?

error[E0532]: expected tuple struct/variant, found struct `OccupiedEntry`
  --> src/main.rs:27:13
   |
27 |             OccupiedEntry(entry) => entry.get_mut().push(name),
   |             ^^^^^^^^^^^^^ did you mean `OccupiedEntry { /* fields */ }`?

我不确定自己在做什么错.这些错误是什么意思,我该怎么做才能解决它们并使我的代码编译?

I'm not exactly sure what I'm doing wrong. What do these errors mean, and what can I do to fix them and get my code to compile?

推荐答案

您需要了解枚举变量与该变量类型之间的区别. Entry的变体是VacantOccupied.您需要匹配这些变体,而不是它们的类型.

You need to understand the difference between an enum variant and the type of that variant. The variants of Entry are Vacant, and Occupied. You need to match against those variants, not their types.

一种修改代码的方法如下:

One way to fix your code would be like this:

use std::collections::hash_map::Entry::{Vacant, Occupied};
match employees.entry(department) {
    Vacant(entry) => { entry.insert(vec![name]); },
    Occupied(mut entry) => { entry.get_mut().push(name); },
}

但是更简单的解决方案是使用or_insert的返回值(将其作为对向量的引用),并将其压入该向量.

But a much simpler solution would to use the return value of or_insert, which is a reference to the vector, and push onto it.

employees
    .entry(department)
    .or_insert(Vec::new())
    .push(name);

这篇关于如何在将字符串与字符串向量配对的哈希映射的值中添加元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆