Zebrafish
Zebrafish

Reputation: 14308

Why do I have to borrow the reference if the return value is already a reference?

In the following code I use the square bracket operator on a HashMap:

let mut my_hash_map: HashMap<u32, String> = HashMap::new();
my_hash_map.insert(5, "value".to_string());
let my_val = my_hash_map[&5];

The square bracket operator of HashMap is supposed to return a reference to the String so I assume that the return type is &String. However the error I get is:

cannot move out of index of HashMap<u32, String> move occurs because value has type String, which does not implement the Copy trait

And I have to explicitly borrow or put an ampersand here:

let my_val = &my_hash_map[&5];

If a reference is already returned, why do I need to borrow with & ???

Upvotes: 0

Views: 38

Answers (0)

Related Questions