use std::collections::HashMap;
struct X {
things: HashMap<String, Vec<String>>,
}
impl X {
fn add_to_things(&mut self, key: &str, value: &str) {
let elements = self.things.entry(key.to_string()).or_default();
elements.push(value.to_string());
self.things.insert(key.to_string(), elements.to_vec());
}
}
fn main() {}
I get the follwing error:
error[E0499]: cannot borrow `self.things` as mutable more than once at a time
--> src/main.rs:11:9
|
9 | let elements = self.things.entry(key.to_string()).or_default();
| ----------- first mutable borrow occurs here
10 | elements.push(value.to_string());
11 | self.things.insert(key.to_string(), elements.to_vec());
| ^^^^^^^^^^^ -------- first borrow later used here
| |
| second mutable borrow occurs here
error: aborting due to previous error
I think I understand where this error comes from and what it means but apparently I don't understand borrowing well enough to come up with a working solution without returning a new struct. Is the whole concept wrong or is there a better solution?
Also feel free to point out any stylistic mistakes.
Thanks.
Anyway, why you need that insert call? In your example it just replace already-modified vector with clone of itself, semantically nothing except bunch of memory allocations and memcpy.
@vitalyd I hadn't looked at the raw entry API since it looked too fearsome for something as basic as to-owned-on-insert, but the discussion you linked to is very informative, thanks