I'm doing some experiments with lifetimes and the borrow checker. Imagine this first struct:
struct First {}
impl First {
fn new() -> Self {
Self {}
}
fn second(&self) -> Second {
Second::new(self)
}
fn hello(&self) {
println!("Hello");
}
}
And the second, which has a lifetime constraint that depends on First:
struct Second<'a> {
owner: &'a First,
}
impl<'a> Second<'a> {
fn new(owner: &'a First) -> Self {
Self { owner }
}
fn hello(&self) {
self.owner.hello();
}
}
The code above works perfectly fine: Second is created by First, and it cannot outlive First.
The problem
Now let's modify Second so it can create a third struct, Third:
struct Second<'a> {
owner: &'a First,
}
impl<'a> Second<'a> {
fn new(owner: &'a First) -> Self {
Self { owner }
}
fn third(&self) -> Third {
Third::new(self.owner)
}
fn hello(&self) {
self.owner.hello();
}
}
And Third itself, which also depends on First:
struct Third<'a> {
owner: &'a First,
}
impl<'a> Third<'a> {
fn new(owner: &'a First) -> Self {
Self { owner }
}
fn hello(&self) {
self.owner.hello();
}
}
I would imagine that, when creating an instance of Third, it would depend on First, but that's not the case. Actually Third depends on Second:
fn main() {
let f = First::new();
let t = {
let sss = f.second();
sss.third() // error: sss does not live long enough
};
}
So, how can I make the lifetime constraint "pass through" from First to Third?