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.