I am doing the third exercise of the second edition of the Book - chapter 8.3 HashMaps - Hash Maps - The Rust Programming Language
Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in a company. For example, “Add Sally to Engineering” or “Add Amir to Sales.” Then let the user retrieve a list of all people in a department or all people in the company by department, sorted alphabetically.
This is the data structure I have created for maintaining a list of employees by department.
HashMap<&str, Vec<&str>>
The key &str
is going to store the names of departments. The value Vec<&str>
is going to store a list of employees by a department.
Objective:
Try to find an entry in
HashMap<&str, Vec<&str>>
(people_by_department
) by&str
(department
). If it does - it willpush
the&str
(employee_name
) intoVec<&str>
(employees_by_department
). Otherwise - it creates a newVec<&str>
.
The code:
let mut people_by_department: HashMap<&str, Vec<&str>> = HashMap::new();
let employee_name = "John";
let department = "Engineering";
match people_by_department.get(&department) {
Some(&employees_by_department) => {
employees_by_department.push(employee_name);
},
None => {
people_by_department.insert(department, vec![employee_name]);
}
}
This is not working. And throwing error.
error[E0596]: cannot borrow immutable local variable `employees_by_department` as mutable
--> src/main.rs:10:9
|
9 | Some(&employees_by_department) => {
| ----------------------- consider changing this to `mut employees_by_department`
10 | employees_by_department.push(employee_name);
| ^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow mutablyerror[E0596]: cannot borrow immutable local variable `employees_by_department` as mutable
--> src/main.rs:10:9
|
9 | Some(&employees_by_department) => {
| ----------------------- consider changing this to `mut employees_by_department`
10 | employees_by_department.push(employee_name);
| ^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow mutably
If I follow the help provided by the compiler, it doesn't fixes it. It produces another problem. I think I am missing something. Need help. Thanks.