Consider the following struct:
struct State<'a> {
parent: Option<&'a mut State<'a>>,
// ...
}
My state stores some values that I might need later. Now I want to implement substates, i.e. allow the manipulation of those values in the substate without touching the parent state, but forwarding lookup of values not in the substate to its parent. Unfortunately, I need a mutable reference to every parent state at all times. I tried the following, but it doesn't work (Playground):
impl<'a> State<'a> {
fn substate<'b>(&'b mut self) -> State<'b>
where
'a: 'b,
{
State::<'b> { parent: Some(self) }
}
}
This gives the following error message:
error[E0308]: mismatched types
--> src/main.rs:10:36
|
10 | State::<'b> { parent: Some(self) }
| ^^^^ lifetime mismatch
|
= note: expected mutable reference `&mut State<'b>`
found mutable reference `&mut State<'a>`
note: the lifetime `'b` as defined here...
--> src/main.rs:6:17
|
6 | fn substate<'b>(&'b mut self) -> State<'b>
| ^^
note: ...does not necessarily outlive the lifetime `'a` as defined here
--> src/main.rs:5:6
|
5 | impl<'a> State<'a> {
| ^^
I don't understand why the compiler wants 'b
to outlive 'a
. In fact, the parent of a state will always live longer than its substate, so in my case the opposite is always true. So why can't the compiler just downgrade the "longer" lifetime 'a
into the "shorter" lifetime 'b
?