recently I faced with a problem that I need to enclose the 'self lifetime inside the struct itself:
struct MyStruct<'self> { // but it should't be exposed
data: Vec<Item>,
id_map: HashMap<u32, &'self Item> // id_map it refer to some self.data's Item
}
enclosing lifetimes for traits is looks something like for<'a> MyTrait<'a>;
Proposal:
Implicilty add 'self to every struct, and propogate it to all inner structs:
struct MyStruct { // it will has <'self> implicitly
inner: AnotherStruct, // it will has <'self> also implicitly
other: &'self Item, // or ecplicitly
}
But extending '_ and elision to structs does sound interesting. Then you could have
struct MyStruct<'_> {
inner: AnotherStruct<'_>, // Has a lifetime, but it's the same one
outer: NoLifetimeHere, // No '_, so you know there's no lifetime
other: &Item, // Same lifetime again, but like in fn elision you don't need the '_ explicitly
}
This is an example of self-referential struct that is not supported in Rust. Not because of lack of annotations, but because it’s unsafe. Assignment to self.data = Vec::new() would create dangling pointers in self.id_map.
Yep, as @kornel said, that’s unfortunately a rather inexpressible pattern in current Rust. You might find https://crates.io/crates/rental crate useful too solve your particular problem, but the solution won’t be pretty at all.