Construction of an object allocates data needed for lifetime of that object, but also creates another object that needs to keep references to the data:
pub fn new() -> Obj {
let data = compute();
Obj {
original: data,
processed: AnotherObj {
reference: &data
}
}
}
Is it possible to express this in Rust's terms?
Here I'd like Obj, AnotherObj and data to have the same lifetime, and of course outlive the new() call.
A raw design of the structs based on your requirements might look like this:
However it's very tricky to get working (personally, I wasn't able to) because you want the
'ainAnotherObj<'a>to be the lifetime oforiginal. However you must supply a lifetime toObj<'a>and thus you would have to specifyObj<'tbc>where'tbcis the lifetime of theObjto be created.I suggest the following alternatives:
1. Make AnotherObj actually own the original
Why not?
Objwill ownAnotherObj, so it can still have access tooriginalas a nested child:2. Shared pointer design
Straightforward use of refcounted pointers:
3. With raw pointers
Options 1. and 2. will bring you the peace of mind of the safe Rust gods, therefore I don't recommend this third option. I still post it here for completeness. Note: it compiles, but I never tested it at runtime, so it may bite. There's only safe code below but you'll have to go in
unsafeland when you want to dereference the raw pointer.