有人能告诉我以下代码中的生命周期错误是什么吗?(从我的实际代码简化而来)我自己看了一遍,但是我无法弄清楚哪里出了问题或如何修复它。当我尝试添加Cell
时出现问题,但我不确定原因。
use std::cell::Cell;
struct Bar<'a> {
bar: &'a str,
}
impl<'a> Bar<'a> {
fn new(foo: &'a Foo<'a>) -> Bar<'a> { Bar{bar: foo.raw} }
}
pub struct Foo<'a> {
raw: &'a str,
cell: Cell<&'a str>,
}
impl<'a> Foo<'a> {
fn get_bar(&self) -> Bar { Bar::new(&self) }
}
编译器错误是:
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
--> src/foo.rs:15:32
|
15 | fn get_bar(&self) -> Bar { Bar::new(&self) }
| ^^^^^^^^
Cell
具有内部可变性有关,这可能会影响包含类型的生命周期差异。将可变性引入混合物中往往会使借用检查器更加严格。我会给出更详细的答案,但这是我自己不太确定的一个方面。 - DK.