stevensonmt
stevensonmt

Reputation: 732

How to extend a Vec<String> as HashMap value?

I have a HashMap<String, Vec<String>>. I cannot figure out how to update the value by growing the Vec. I thought the following would work:

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()]);
    }
}

but it instead gives the error

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()])
   |              ^^^^^^

Upvotes: 2

Views: 739

Answers (2)

stevensonmt
stevensonmt

Reputation: 732

After thinking about the entry API a little more I came up with the following solution:

let val = data.entry(department.to_string())
                .or_insert(vec!());

        val.extend(vec!(employee.to_string()));

Upvotes: 2

Boiethios
Boiethios

Reputation: 42849

Use this code:

use std::collections::hash_map::Entry;

match data.entry(department.to_string()) {
    Entry::Occupied(mut entry)  => { entry.get_mut().push(employee.to_string()); },
    Entry::Vacant(entry)        => { entry.insert(vec!(employee.to_string())); },
}
  • If the key exists, get a mutable reference on the value and add the new string,
  • Else, create a new vector and insert it in the hashmap.

All this information is in the documentation.

Upvotes: 1

Related Questions