Recursive lifetime issue: child holding a reference to a parent of the same type
⚓ Rust 📅 2025-12-14 👤 surdeus 👁️ 9Hi!
I need to have a tree-like data structure, where every node is the same type, and where each child references it's parent. I tried different things, and eventually found one working, but I can't tell why it's working.
Some minimal example code is here in the playground.
In short, I want somthing like:
pub enum Tree<'parent> {
Root,
Child(&'parent Tree<'idk-what-to-put-here>),
}
Of course, this code doesn't work.
The solution I found (in the playground) is really weird:
enum Tree<'parent, 'grandparent> {
Root,
Child(&'parent Tree<'grandparent, 'parent>),
}
In the 0 field of Child, the 'grandparent and 'parent lifetimes are... inverted? compared to the order of the arguments in the struct. It's weird.
The closest post I found about this problem is this one, but I couldn't find a satisfactory answer here.
Can someone give me an explanation to this? And eventually a better solution?
4 posts - 4 participants
🏷️ Rust_feed