我有HashMap<String, Vec<String>>
。它是部门到每个员工列表的映射。如果该部门的条目已经存在,它将采用向量并将其添加到员工中,否则它将创建一个新的向量并将其作为该部门的值插入:
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
}
是否有比目前正在做的方法更清洁的方法?现在对我来说似乎很混乱。
我已经查找了这些问题。