Hello. I have the following piece of code:
use std::collections::HashMap;
struct Item {
name: String,
level: u8,
children_by_names: Vec<String>,
children_by_level: HashMap<u8, String>
}
struct App {
items_by_name: HashMap<String, Item>
}
impl App {
pub fn process(&mut self) {
for (_, item) in &self.items_by_name {
for name_of_child in &item.children_by_names {
let child = self.items_by_name.get_mut(name_of_child).unwrap();
child.children_by_level.insert(item.level, item.name.clone());
}
}
}
}
fn main() {
println!("Started");
}
And of course I receive the following error:
error[E0502]: cannot borrow `self.items_by_name` as mutable because it is also borrowed as immutable
--> src/main.rs:18:29
|
16 | for (_, item) in &self.items_by_name {
| -------------------
| |
| immutable borrow occurs here
| immutable borrow later used here
17 | for name_of_child in &item.children_by_names {
18 | let child = self.items_by_name.get_mut(name_of_child).unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
For more information about this error, try `rustc --explain E0502`.
error: could not compile `playground` due to previous error
I understand why, but don't know how to solve it.
What is the best way to do this?