Reputation: 14308
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 typeString
, which does not implement theCopy
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