I want to store a collection of children each holding a reference to its parent.
The following example won't compile (playground).
struct Parent<'p> {
children: Vec<Child<'p>>,
}
struct Child<'p> {
parent: &'p Parent<'p>
}
fn main() {
let mut parent = Parent {children: vec![]};
let child = Child{parent: &parent};
parent.children.push(child);
}
Is there a way to create such a cyclic reference without introducing smart pointers but with plain references? Maybe some unsafe can help?
If not, what might a minimal working example look like?
UPD: to ensure that the parent won't be dropped while a child is created, let's introduce a special method of Parent, but it also won't compile for an obvious reason:
impl<'p> Parent<'p> {
fn add_child(&'p mut self) {
let child = Child{parent: &self};
self.children.push(child);
}
}
UPD2: what if there may be no "orphan" children and they should always be owned by a parent?