0

I can't figure out how to modify the value returned by Some:

fn add_employee(
    employees: &mut HashMap<String, Vec<String>>,
    employee_name: &String,
    department_name: &String,
) {
    match employees.get(department_name) {
        Some(members) => {
            members.push(employee_name.clone()); // what I want, but it doesn't work
        }
        None => {}
    }
}

The compiler complains:

error[E0596]: cannot borrow immutable borrowed content `*members` as mutable
  --> src/main.rs:10:13
   |
10 |             members.push(employee_name.clone());
   |             ^^^^^^^ cannot borrow as mutable
Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
Jet Blue
  • 4,589
  • 5
  • 33
  • 43
  • 1
    Prefer using an `if let` instead of a one-armed `match`. [Accept `&str` instead of `&String`](https://stackoverflow.com/q/40006219/155423). My intuition says you will really want the [entry API](https://stackoverflow.com/q/28512394/155423). – Shepmaster Oct 30 '17 at 23:45

1 Answers1

4

Use get_mut() instead of get().

Stefan
  • 4,914
  • 1
  • 21
  • 40