In my project, I want to iterate over a simple Vec
and update a HashMap
using another function, but I'm stuck with the borrow checker complaining that it cannot borrow *self
as mutable more than once at a time.
Here is an example:
use std::collections::HashMap;
struct Test {
entries: Vec<String>,
objects: HashMap<String, String>,
}
impl Test {
fn new(entries: Vec<String>) -> Test {
Test {
entries,
objects: HashMap::new(),
}
}
fn process(&mut self) {
for entry in self.entries.iter_mut() {
self.update(entry);
}
}
fn update(&mut self, entry: &String) {
self.objects
.entry(entry.to_owned())
.or_insert(entry.to_owned());
}
}
fn main() {
let mut test = Test::new(vec!["abc".to_owned(), "def".to_owned()]);
test.process();
}
And the resulting error:
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src\main.rs:18:13
|
17 | for entry in self.entries.iter_mut() {
| -----------------------
| |
| first mutable borrow occurs here
| first borrow later used here
18 | self.update(entry);
| ^^^^ second mutable borrow occurs here
I do understand why the error occurs but I don't know how to fix it. Any idea?