Jet Blue
Jet Blue

Reputation: 5291

How do you make the value of a Some returned from HashMap::get mutable?

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

Upvotes: 0

Views: 57

Answers (1)

Stefan
Stefan

Reputation: 5530

Use get_mut() instead of get().

Upvotes: 4

Related Questions