Push to Vector in Hashmap

Viewed 53

Goal: Create a hashmap, add a vector to the hashmap, push to the vector

Code:

use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();

    map.insert("first", Vec::new());

    let get_option = map.get("first");

    match get_option {
        None => println!("invalid key"),
        Some(v) => v.push("Chris"),
    }
}

Error:

error[E0596]: cannot borrow `*v` as mutable, as it is behind a `&` reference
  --> src/main.rs:12:20
   |
12 |         Some(v) => v.push("Chris"),
   |              -     ^^^^^^^^^^^^^^^ `v` is a `&` reference, so the data it refers to cannot be borrowed as mutable
   |              |
   |              help: consider changing this to be a mutable reference: `&mut Vec<&str>`
1 Answers

Your hashmap is mutable, but HashMap::get always returns an immutable reference. If you want a mutable reference to an element, use HashMap::get_mut.

let get_option = map.get_mut("first");

match get_option {
    None => println!("invalid key"),
    Some(v) => v.push("Chris"),
}

You'll see this a lot in Rust: a _mut version and a non-mutable version side-by-side. The idea of having mutability-polymorphic functions (a function whose mut status is a generic argument like a lifetime) has been floated before to the language developers, but it's usually been dismissed as too complicated and not worth the cost.

Related