Just curious regarding ownership and the HashMap API. I think I misunderstand both.
use std::collections::HashMap;
fn foo() {
let mut hm: HashMap<u8, Vec<String>> = HashMap::new();
let a = "abc".to_owned();
hm.entry(0)
.and_modify(|e| e.push(a))
.or_insert(vec![a]);
}
We get this:
error[E0382]: use of moved value: `a`
--> src/main.rs:99:25
|
96 | let a = "abc".to_owned();
| - move occurs because `a` has type `std::string::String`, which does not implement the `Copy` trait
97 | hm.entry(0)
98 | .and_modify(|e| e.push(a))
| --- - variable moved due to use in closure
| |
| value moved into closure here
99 | .or_insert(vec![a]);
| ^ value used here after move
For more information about this error, try `rustc --explain E0382`.
How would you solve this idiomatically and why? I assume there is a better solution than:
fn foo() {
let mut hm: HashMap<u8, Vec<String>> = HashMap::new();
let a = "abc".to_owned();
hm.entry(0)
.and_modify(|e| e.push(a.clone()))
.or_insert(vec![a]);
}
Thank you!