Reputation: 21
Im new to Rust, and i'm having this problem where I need to keep a Vec of Child in the Parent struct, and each child needs to be able to use the Parent functions, so with some research I ended up with this, however , its not really working, as I always end up with the same error:
Cannot borrow
self.children
as mutable, as it is behind a&
referenceself
is a&
reference, so the data it refers to cannot be borrowed as mutable)*
This is a simplified version of my real code, but it has the same problem. I need to do the add_child from within Parent, because in the real code it has more functionality that depends on the Parent that helps create the Child.
struct Parent<'a> {
children: Vec<Child<'a>>,
}
impl<'b> Parent<'b> {
fn add_child(&'b self) -> () {
let child = Child::new(&self);
self.children.push(child);
}
fn do_stuff(&self) -> () {
self.add_child();
self.add_child();
}
}
struct Child<'a> {
parent: &'a Parent<'a>,
}
impl<'a> Child<'a> {
fn new(parent: &'a Parent<'a>) -> Child<'a> {
Child { parent }
}
}
I also came up with some different workarounds, like defining Vec<Child>
outside the Parent struct, in the main fn, but that doesnt really help me, because I need to use them in Parent later.
Upvotes: 0
Views: 161