I want to iterate through a vector of pointers. The vector is contained inside a struct, and the pointer points to the same struct, like a tree.
The vector is self.groups. I tried to loop over it, and call a (mutable) method, push_group(), but I got the error error[E0596]: cannot borrow **g as mutable, as it is behind a & reference.
I tried adding iter_mut(), but it didn't seem to do anything.
Am I doing something wrong ?
Playground : https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=14d911a460079a4eb747d6b10361fa60
The code for reference :
pub struct Group<'a> {
pub name: String,
pub groups: Vec<&'a Group<'a>>
}
impl<'a> Group<'a> {
// Append a node under a node named "parent_name"
pub fn push_group(&mut self, group: &'a Group<'a>, parent_name: &str) -> bool {
if self.name == parent_name {
self.groups.push(group);
return true;
}
for g in self.groups.iter_mut() {
let found = g.push_group(group, parent_name); // Error: cannot borrow as mutable
if found {
return found;
}
}
false
}
}
fn main() {
let mut group = Group { name: "PATIENT_RESULT".to_string(), groups: vec![] };
let other_group = Group { name: "OBSERVATION".to_string(), groups: vec![] };
let _ = group.push_group(&other_group, "PATIENT_RESULT");
}