由于递归结构体中存在冲突要求,无法推断出适当的生命周期。

8
当我尝试编译这段代码时:
pub struct Context<'a> {
    pub outer: Option<&'a mut Context<'a>>,
}

impl<'a> Context<'a> {
    pub fn inside(outer: &'a mut Context) -> Context<'a> {
        Context { outer: Some(outer) }
    }
}

我遇到了这个错误:

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
 --> src/main.rs:7:9
  |
7 |         Context { outer: Some(outer) }
  |         ^^^^^^^
  |
note: first, the lifetime cannot outlive the lifetime 'a as defined on the impl at 5:1...
 --> src/main.rs:5:1
  |
5 | / impl<'a> Context<'a> {
6 | |     pub fn inside(outer: &'a mut Context) -> Context<'a> {
7 | |         Context { outer: Some(outer) }
8 | |     }
9 | | }
  | |_^
note: ...so that expression is assignable (expected Context<'a>, found Context<'_>)
 --> src/main.rs:7:9
  |
7 |         Context { outer: Some(outer) }
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: but, the lifetime must be valid for the anonymous lifetime #1 defined on the method body at 6:5...
 --> src/main.rs:6:5
  |
6 | /     pub fn inside(outer: &'a mut Context) -> Context<'a> {
7 | |         Context { outer: Some(outer) }
8 | |     }
  | |_____^
note: ...so that expression is assignable (expected &mut Context<'_>, found &mut Context<'_>)
 --> src/main.rs:7:31
  |
7 |         Context { outer: Some(outer) }
  |                               ^^^^^

为什么会发生这种情况?

2
始终提供一个[MCVE](不要说“这在其他地方已经定义了,但我不会告诉你它是什么”),并包含完整的错误消息。 - Shepmaster
1个回答

5

这是因为您没有满足所需的义务。

由于生命周期省略,您的代码等效于:

pub fn inside<'b>(outer: &'a mut Context<'b>) -> Context<'a>

将你的代码更改为

pub fn inside(outer: &'a mut Context<'a>) -> Context<'a>

它将被编译。


谢谢,它起作用了!我完全忘记了outer参数上的生命周期参数。 - Zac
1
不错的技巧:当面对这样的问题时,将隐式生命周期放入声明中可以简化推理,因为它使问题立即可见! - Nawaz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接