锈蚀寿命错误 [英] Rust lifetime error
问题描述
在下面的代码中,谁能说出生命周期错误? (从我的实际代码简化)我已经仔细检查了一下,但是我无法弄清楚什么是错误的或如何解决的.当我尝试添加Cell
时出现问题,但是我不确定为什么.
Can anyone tell what the lifetime error is in the following code? (simplified from my actual code) I've looked it over myself, but I can't figure out what is wrong or how to fix it. The problem comes when I try to add the Cell
, but I'm not sure why.
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) }
| ^^^^^^^^
推荐答案
首先,解决方案:
use std::cell::Cell;
struct Bar<'a> {
bar: &'a str,
}
impl<'a> Bar<'a> {
fn new(foo: &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<'a> { Bar::new(&self) }
}
您的代码中有两个问题.第一个是get_bar
,您没有指定返回类型的生存期.当您未在签名中指定生存期时,Rust不会推断正确的生存期,它只是根据简单的规则盲目地将其填充.在这种特定情况下,鉴于self.raw
的生命周期(实际上是您想要的)是'a
,因此您得到的实际上是fn get_bar<'b>(&'b self) -> Bar<'b>
.请参阅终生淘汰上的Rust Book章节.
There are two problems in your code. The first is with get_bar
, where you didn't specify the lifetime for the return type. When you don't specify lifetimes in signatures, Rust doesn't infer the correct lifetimes, it just blindly fills them in based on simple rules. In this specific case, what you get is effectively fn get_bar<'b>(&'b self) -> Bar<'b>
which is obviously wrong, given the lifetime of self.raw
(which was what you actually wanted) is 'a
. See the Rust Book chapter on Lifetime Elision.
第二个问题是您过度限制了Bar::new
的参数. &'a Foo<'a>
表示只要借用的字符串存在,就需要借用Foo
.但是类型中的借用必须超出该类型的值,因此在这种情况下有效的 only 生存期是'a
与要借用的事物的整个生存期相匹配...和 与get_bar
的签名冲突(您在这里说&self
不一定要活到'a
,因为它有自己的生存期).长话短说:从Foo
借书中删除不必要的'a
,仅保留&Foo<'a>
.
The second problem is that you're over-constraining the argument to Bar::new
. &'a Foo<'a>
means you require a borrow to a Foo
for as long as the strings it's borrowing exist. But borrows within a type have to outlive values of said type, so the only lifetime valid in this case is where 'a
matches the entire lifetime of the thing being borrowed... and that conflicts with the signature of get_bar
(where you're saying &self
won't necessarily live as long as 'a
since it has its own lifetime). Long story short: remove the unnecessary 'a
from the Foo
borrow, leaving just &Foo<'a>
.
改写上面的内容:get_bar
的问题是您没有编写足够的约束,而Bar::new
的问题是您编写了太多约束.
To rephrase the above: the problem with get_bar
was that you hadn't written enough constraints, the problem with Bar::new
was that you'd written too many.
这篇关于锈蚀寿命错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!