utopman
utopman

Reputation: 617

Rust : insert uint in hashmap reference

I am new to Rust and I have this error at compilation time but I don't get it

error[E0614]: type `Option<u32>` cannot be dereferenced
 --> src/main.rs:9:5
  |
9 |     *mymap.insert("hello world", 0);
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Here is my code simplified to reproduce the issue:

use std::collections::HashMap;

fn main() {
    let mymap: HashMap<&str, u32> = HashMap::new();
    f(&mymap)
}

fn f(mymap: &HashMap<&str, u32>) {
    *mymap.insert("hello world", 0);
}

Also the following does not work either

*mymap.insert("hello world", &0);

I don't find the root cause of my problem by googling it, I think I don't have the words. It looks like some borrowing issue.

Upvotes: 1

Views: 180

Answers (2)

vallentin
vallentin

Reputation: 26245

You're actually not dereferencing mymap, you're actually dereferencing the result of insert(), because dereferencing (i.e. *) have a weaker precedence than a method call.

So it complains about dereferencing an Option<u32> because that's what insert() returns. If you actually wanted to dereference mymap you'd have to write (*mymap).insert("hello world", 0);. However, that is not needed in Rust.

If you remove the * then you will get a second problem, which is that you're attempting to mutate mymap, which is an immutable reference. So to be able to insert, i.e. mutate mymap in f, you need to pass it a mutable reference, i.e. mymap: &mut HashMap<&str, u32>.

use std::collections::HashMap;

fn main() {
    let mut mymap: HashMap<&str, u32> = HashMap::new();
    f(&mut mymap)
}

fn f(mymap: &mut HashMap<&str, u32>) {
    mymap.insert("hello world", 0);
}

Upvotes: 3

pretzelhammer
pretzelhammer

Reputation: 15165

You don't need to dereference references on method calls, Rust will automatically do that for you. Also, you need to pass a mutable reference of mymap so you can actually perform the insert. Fixed example:

use std::collections::HashMap;

fn main() {
    let mut mymap: HashMap<&str, u32> = HashMap::new();
    f(&mut mymap)
}

fn f(mymap: &mut HashMap<&str, u32>) {
    mymap.insert("hello world", 0);
}

playground

Upvotes: 1

Related Questions