How can I retrive a mutable vector from a HashMap?

Hello,

I'm learning Rust and I was trying to complete one of the excercise of The Book and the way I'm trying to resolve it is to use a HashMap<String, Vec>. Once I add a value to that map I don't know how to retrieve the value ( Vec<String> ) as mutable to add another element to that Vec.

This is what I'm trying to do:

use std::collections::HashMap;

fn main() {
    let mut company: HashMap<String, Vec<String>> = HashMap::new();
    company.insert("Finance".to_string(), vec!["Sam Robertson".to_string()] );

    let mut finance = company.get("Finance");
    if let Some(f) = finance {

        ////////////////////////////////////////////////////////////////
        // How do I make f mutable so I can add a value to the vector //
        f.push("Frank McLeod".to_string());
        ////////////////////////////////////////////////////////////////
    }

    for (dept, employees) in company {
        println!("Department: {}", dept);
        for employee in employees {
            println!("\t- {}", employee);
        }
    }
}

My problem is in line 12, how do I get that as a mutable reference to be able to push a new item to the Vec<String>. The compiler gives me the following error:

error[E0596]: cannot borrow `*f` as mutable, as it is behind a `&` reference
  --> src/main.rs:12:9
   |
8  |     if let Some(f) = finance {
   |                 - help: consider changing this to be a mutable reference: `&mut std::vec::Vec<std::string::String>`
...
12 |         f.push("Frank McLeod".to_string());
   |         ^ `f` is a `&` reference, so the data it refers to cannot be borrowed as mutable

Can somebody please help me or give me some clues?

    let finance = company.get_mut("Finance");
    if let Some(f) = finance {

        ////////////////////////////////////////////////////////////////
        // How do I make f mutable so I can add a value to the vector //
        f.push("Frank McLeod".to_string());
        ////////////////////////////////////////////////////////////////
    }

Playground

The get() method returns an immutable reference. You need to use get_mut() to get a mutable one!

Edits: Posted before testing and made several mistakes.

1 Like

I tried annotating with &mut here and there but it never occurred to me to look for a method that returns a mutable reference :tired_face:

Thank you! @Yoshanuikabundi :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.