像许多新的 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
的变体是 Vacant
和 Occupied
。您需要匹配这些变体,而不是它们的类型。
修复代码的一种方法是这样的:
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/