我有一个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()]);
}
}
但它却给出了错误
error: no method named `extend` found for type `std::collections::hash_map::Entry<'_, std::string::String, std::vec::Vec<std::string::String>>` in the current scope
--> src/main.rs:27:14
|
27 | .extend(vec![employee.to_string()])
| ^^^^^^
最佳答案
在对入口 API 进行了更多思考之后,我想出了以下解决方案:
let val = data.entry(department.to_string())
.or_insert(vec!());
val.extend(vec!(employee.to_string()));
关于vector - 如何将 Vec<String> 扩展为 HashMap 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44929300/