本文介绍了由于递归结构中的需求冲突,因此无法推断出适当的生存期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试编译此代码时:
When I try to compile this code:
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) }
| ^^^^^
为什么会这样?
推荐答案
这是因为您没有满足所需的义务.
This is because you haven't met the obligations that you require.
由于终身删除,您的代码等效于:
Due to lifetime elision, your code is equivalent to:
pub fn inside<'b>(outer: &'a mut Context<'b>) -> Context<'a>
将代码更改为
pub fn inside(outer: &'a mut Context<'a>) -> Context<'a>
它将编译.
这篇关于由于递归结构中的需求冲突,因此无法推断出适当的生存期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!