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
  • 388,571
  • 95
  • 1,107
  • 1,366
Jet Blue
  • 5,109
  • 7
  • 36
  • 48
  • 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
  • 5,304
  • 2
  • 25
  • 44