vector - 如何将一个元素添加到将字符串与字符串向量配对的 HashMap 的值中?

标签 vector hashmap rust

像许多新的 Rustaceans 一样,我一直在努力通过 Rust Book .我正在阅读关于集合的章节,但我卡在 one of the exercises 上了.内容如下:

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.

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

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 */ }`?

我不确定我做错了什么。这些错误是什么意思,我可以做些什么来修复它们并让我的代码编译?

最佳答案

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

修复代码的一种方法是这样的:

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 的返回值,这是对向量的引用,并将其推送到它上。

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

关于vector - 如何将一个元素添加到将字符串与字符串向量配对的 HashMap 的值中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53368852/

相关文章:

c++ - 在 const 迭代器上调用成员函数

c++ - 使用 for_each 计算 vector 中每个元素的平方和

java - 泛型:如何在不强制转换的情况下获取 map 的值

java - 在 iReport 中初始化 HashMap 变量

rust - 来自特征和 T 生命周期的 Vec<T> 引用

c++ - 第二行列数较少 "cuts off"第一行列数较多

c++ - 在 C++ 中查找 const vector 中 4 个最大值的迭代器的最有效方法

java - HashMap 中的 ArrayList<Object> 之谜

rust - 如何解决 TcpStream 的 "moved value"问题?

rust - 使用into_serde反序列化字符串使应用程序 panic