0

I have HashMap<String, Vec<String>>. It is a map of departments to a list of employees in each of them. If an entry for the department already exists, it takes the vector and adds the employee to it, otherwise it creates a new vector and inserts it as value for the department:

use std::{
    collections::{hash_map::Entry::*, HashMap},
    io,
};

fn create_map_of_employees(number_of_employees: &i32) -> HashMap<String, Vec<String>> {
    let mut employee_department_map: HashMap<String, Vec<String>> = HashMap::new();

    for _ in 0..*number_of_employees {
        let mut employee_name = String::new();
        let mut department_name = String::new();
        println!("Enter Employee name:");
        io::stdin()
            .read_line(&mut employee_name)
            .expect("Input Error");

        println!("Enter Department name:");
        io::stdin()
            .read_line(&mut department_name)
            .expect("Input Error");

        match employee_department_map.entry(String::from(department_name.trim())) {
            Occupied(o) => {
                let vector = o.into_mut();
                vector.push(String::from(employee_name.trim()));
            }
            Vacant(v) => {
                v.insert(vec![String::from(employee_name.trim())]);
            }
        }
    }
    employee_department_map
}

Is there a cleaner way to do this than what is currently being done? It seems a very messy to me right now.

I have already looked up on these questions.

leoOrion
  • 1,833
  • 2
  • 26
  • 52
  • 1
    `employee_department_map.entry(String::from(department_name.trim())).or_insert_with(Vec::new).push(String::from(employee_name.trim()));` – Shepmaster Dec 26 '18 at 19:12
  • Stackoverflow is not here to post question about already working code. Better ask on the chat, https://chat.stackoverflow.com/rooms/62927/rust, for little tips about how to write code in more elegant way. – Stargateur Dec 26 '18 at 19:15
  • `&i32` => `i32`, there is no gain to use a reference for Copy type. – Stargateur Dec 26 '18 at 19:16

0 Answers0