【发布时间】:2022-06-29 02:36:27
【问题描述】:
考虑以下结构:
struct State<'a> {
parent: Option<&'a mut State<'a>>,
// ...
}
我的状态存储了一些我以后可能需要的值。现在我想实现子状态,即允许在不触及父状态的情况下操作子状态中的这些值,但将不在子状态中的值的查找转发到其父状态。不幸的是,我始终需要对每个父状态的可变引用。我尝试了以下方法,但它不起作用(Playground):
impl<'a> State<'a> {
fn substate<'b>(&'b mut self) -> State<'b>
where
'a: 'b,
{
State::<'b> { parent: Some(self) }
}
}
这会给出以下错误消息:
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> {
| ^^
我不明白为什么编译器希望'b 比'a 寿命更长。事实上,一个状态的父状态总是比它的子状态寿命长,所以在我的情况下,情况总是相反。那么为什么编译器不能将“更长”生命周期'a 降级为“更短”生命周期'b?
【问题讨论】: