7

Can anybody explain why following code does not compile?

use std::collections::HashMap;

fn add(mut h: &HashMap<&str, &str>) {
    h.insert("foo", "bar");
}

fn main() {
    let mut h: HashMap<&str, &str> = HashMap::new();
    add(&h);
    println!("{:?}", h.get("foo"));
}

This is what rustc tells me

hashtest.rs:4:5: 4:6 error: cannot borrow immutable borrowed content `*h` as mutable
hashtest.rs:4     h.insert("foo", "bar");
                  ^

1 Answers1

28

The problem is that you pass a mutable reference to a HashMap (i.e. the reference can be changed to point to another HashMap), and not a reference to a mutable HashMap (i.e. the HashMap can change).

Here is a correct code:

use std::collections::HashMap;

fn add(h: &mut HashMap<&str, &str>) {
    h.insert("foo", "bar");
}

fn main() {
    let mut h: HashMap<&str, &str> = HashMap::new();
    add(&mut h);
    println!("{:?}", h.get("foo"));
}
Valentin Lorentz
  • 9,556
  • 6
  • 47
  • 69