I came across a question the discord channel
struct Node<'a> {
parent: Option<&'a Node<'a>>
}
struct Genealogy<'a> (Vec<&'a Node<'a>>);
impl Genealogy<'_> {
fn root(&self) -> &Node<'_> {
self.0.last().unwrap()
}
}
impl<'a> Node<'a> {
fn genealogy(&self) -> Genealogy<'_> {
let mut current_node = self;
let mut genealogy = vec![current_node];
while current_node.parent.is_some() {
current_node = current_node.parent.unwrap();
genealogy.push(current_node);
}
Genealogy(genealogy)
}
fn root(&'a self) -> &Self {
self.genealogy().0.last().unwrap()
}
fn root_2(&'a self) -> &Self {
self.genealogy().root()
}
}
error[E0515]: cannot return value referencing temporary value
--> src/lib.rs:31:9
|
31 | self.genealogy().root()
| ----------------^^^^^^^
| |
| returns a value referencing data owned by the current function
| temporary value created here
To test my lifetime knowledge, I tried to fix it with named lifetimes and it turned out I didn't really understand what is going on.
I don't understand why the two fn root
make difference, root_2
is semantically the same as root
except it calls an extra method?
fn root(&'a self) -> &Self {
self.genealogy().0.last().unwrap()
}
fn root_2(&'a self) -> &Self {
self.genealogy().root()
}
How do I understand the lifetime here and how do I fix it?