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

标签 vector hashmap rust

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

相关文章:

Rust 中作为可选函数参数的闭包

c++ - 带有静态 std::vector 的内存泄漏(有点)

java - 检查 HashMap 是否被修改(添加或修改值)

java - HashMap.values()/HashMap.keySet()什么时候按引用返回,什么时候按值返回?

rust - Change selector in match when selector is a mutable reference

types - 为什么这个闭包参数需要显式类型?

c++ - 迭代器和二维 vector

c++ - 使用按引用传递检索 vector 不会传播清除底层 vector ?

string - 如何在 Rust 中将字符串转换为向量?

java - 如何让我的方法返回 Collection<Character>