gpt4 book ai didi

vector - 如何将 Vec 扩展为 HashMap 值?

转载 作者:行者123 更新时间:2023-11-29 08:06:13 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com