生锈寿命错误

Ant*_*ony 1 lifetime rust

任何人都可以告诉以下代码中的生命周期错误是什么?(从我的实际代码简化)我自己看了看,但我无法弄清楚出了什么问题或如何解决它.当我尝试添加时会出现问题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) }
}
Run Code Online (Sandbox Code Playgroud)

编译器错误是

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) }
   |                                ^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

DK.*_*DK. 5

一,解决方案:

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) }
}
Run Code Online (Sandbox Code Playgroud)

您的代码中存在两个问题.第一个是get_bar,在那里你没有指定返回类型的生命周期.当你没有在签名中指定生命周期时,Rust不会推断出正确的生命周期,它只是根据简单的规则盲目地填充它们.在这个特定的情况下,你得到的是有效的fn get_bar<'b>(&'b self) -> Bar<'b>,这显然是错误的,考虑到self.raw(你真正想要的)的生命周期'a.请参阅有关Lifetime Elision的Rust Book章节.

第二个问题是你过度约束参数Bar::new. &'a Foo<'a>意味着只要其借用Foo的字符串存在,您就需要借入a .但是,在一个类型中借得活得比说类型的值,所以只有在这种情况下,有效生命周期就是'a匹配借来的东西整个生命周期......和与签名冲突get_bar(如果你说&self亿韩元"只要'a它有自己的生命,就必须活着).长话短说:'aFoo借用中删除不必要的东西,只留下&Foo<'a>.

重新解释上述问题:问题get_bar在于你没有写出足够的约束,问题Bar::new在于你写得太多了.