I am trying to have common struct between parent struct which holds a vector of children structs. CommonParams struct holds parameters the children inherit from the Parent which might be updated and so all children should have access to the up-to-date parameters.
All parent must have 1 child when created.
struct Parent<'a> {
children: Vec<Child<'a>>,
common_params: CommonParams,
name: &'a str,
}
impl<'a> Parent<'a> {
fn new(name: &str, child_name: &str, child_age: u8, address: String) -> Parent<'a> {
let common = CommonParams {
address,
};
let mut parent = Parent {
children: Vec::new(),
common_params: common,
name,
};
let child = Child::new(&parent.common_params, child_name);
parent.add_child(child);
parent
}
fn add_child(&mut self, child: Child<'a>) {
self.children.push(child);
}
}
struct Child<'a> {
common_params: &'a CommonParams,
name: &'a str,
}
impl<'a> Child<'a> {
fn new(common_params: &'a CommonParams, name: &'a str) -> Child<'a> {
Child {
common_params,
name,
}
}
}
struct CommonParams {
address: String,
}
The compiler returns an error:
9 | impl<'a> Parent<'a> {
| -- lifetime `'a` defined here
...
14 | let mut parent = Parent {
| ---------- binding `parent` declared here
...
19 | let child = Child::new(&parent.common_params, child_name);
| --------------------- borrow of `parent.common_params` occurs here
20 | parent.add_child(child);
21 | parent
| ^^^^^^
| |
| move out of `parent` occurs here
| returning this value requires that `parent.common_params` is borrowed for `'a`
How can I implement this?
Thanks