I'm trying to create a struct that references itself (using Option<Box<>>
). I can make something that works using just the struct, but I cannot make it compile when using some container for all of them.
This is the structure I'm trying to create (adapted from real example), that is able to create children that reference to the parent
pub struct Node<'a> {
value: u32,
parent: Option<Box<&'a Node<'a>>>,
}
impl<'a> Node<'a> {
pub fn new_child(&'a self, value: u32) -> Node<'a> {
Node {
value,
parent: Some(Box::new(&self)),
}
}
}
This works. However, when I try to build these nodes using a Graph
-like container, the build fails:
pub trait Graph {
type NodeType;
fn new_child(&self, value: u32) -> Self::NodeType;
}
struct GraphImpl<'a> {
root: Node<'a>,
}
impl<'a> Graph for GraphImpl<'a> {
type NodeType = Node<'a>;
fn new_child(&self, value: u32) -> Self::NodeType {
self.root.new_child(value)
}
}
error:
Compiling playground v0.0.1 (/playground)
error: lifetime may not live long enough
--> src/main.rs:32:9
|
28 | impl<'a> Graph for GraphImpl<'a> {
| -- lifetime `'a` defined here
...
31 | fn new_child(&self, value: u32) -> Self::NodeType {
| - let's call the lifetime of this reference `'1`
32 | self.root.new_child(value)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ associated function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1`
error: could not compile `playground` due to previous error
I've tried adding different lifetime markers at many different places with no success. I've read different questions and answers and it's clear that I'm missing something (and I'm not understanding how lifetimes works in Rust :sad: ). I will really appreciate some help here... and some pointers so I can understand why it works (or it shouldn't work).
Thanks!