Currently, I have a code where I need that Child struct have a reference to field 'x' of its Parent struct. For those needs I did workaround with using Rc<>.
#[derive(Clone)]
pub struct SomeBigStruct {
pub value: u32,
// ... plus many vector properties
}
pub struct ParentV1 {
pub x: SomeBigStruct,
pub children: Vec<ChildV1>,
}
pub struct ChildV1 {
pub x_ref: Rc<SomeBigStruct>,
}
fn new_parent_v1() -> ParentV1 {
let x = SomeBigStruct{value: 42};
let x_ref = Rc::new(x.clone());
ParentV1 {
x,
children: vec![
ChildV1 { x_ref: x_ref.clone() },
ChildV1 { x_ref: x_ref.clone() },
//... plus thousands of another children
],
}
}
This works, but I was wondering that simple reference with lifetime should be also feasible. Because lifetime of struct which I want to refer is known (same as Parent struct lifetime). Something like:
pub struct ParentV2 {
pub x: SomeBigStruct,
pub children: Vec<ChildV2<'lifetime_of_parent_struct>>,
}
pub struct ChildV2<'a> {
pub x_ref: &'a SomeBigStruct,
}
fn new_parent_v2<'a>() -> ParentV2<'a> {
let x = SomeBigStruct{value: 42};
ParentV2 {
children: vec![
ChildV2 { x_ref: &x },
ChildV2 { x_ref: &x },
],
x,
}
}
This of course cannot be compiled because I do not know how define reference only to Parent struct lifetime. Is it even possible? If not is there any better workaround than mine? Thanks.