引用盒装值的生命周期不够长

Lifetime of reference to boxed value does not live long enough

以下代码无法编译:

use std::borrow::Borrow;

struct Inner<'a> {
    v: Vec<&'a u8>,
}

struct Foo<'a> {
    inner: Inner<'a>,
    derp: Box<u8>,
}

impl<'a> Foo<'a> {
    fn new() -> Foo<'a> {
        let mut e = Foo {
            inner: Inner { v: vec![] },
            derp: Box::new(128),
        };
        e.inner.v.push(&*e.derp);

        return e;
    }

    fn derp(&mut self) {
        println!("{:?}", self.inner.v);
    }
}

fn main() {
    let mut f = Foo::new();

    f.derp();
}

我收到以下错误:

error[E0597]: `*e.derp` does not live long enough
  --> src/main.rs:18:25
   |
18 |         e.inner.v.push(&*e.derp);
   |                         ^^^^^^^ does not live long enough
...
21 |     }
   |     - borrowed value only lives until here
   |
note: borrowed value must be valid for the lifetime 'a as defined on the impl at 12:1...
  --> src/main.rs:12:1
   |
12 | / impl<'a> Foo<'a> {
13 | |     fn new() -> Foo<'a> {
14 | |         let mut e = Foo {
15 | |             inner: Inner { v: vec![] },
...  |
25 | |     }
26 | | }
   | |_^

我认为框内的值的寿命与 'a 一样长,因为它是 Foo 的成员,而 Foo 的寿命恰好如此。

我想知道 Foo 在新函数末尾的移动是否混淆了它,所以如果尝试在 derp 中进行追加。我得到一个不同的错误:

error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
  --> main.rs:20:27
   |
20 |         self.inner.v.push(& *self.derp);
   |                           ^^^^^^^^^^

这没有告诉我编译器认为装箱值的生命周期有多长。

I think though that the value inside of the box does live for as long as 'a since it is a member of Foo which has exactly that lifetime.

可以为 derp 成员分配一个新框,此时旧框将被删除,其中值的生命周期结束。

我认为您尝试做的事情在安全 Rust 中是不可能的:不支持结构成员之间的交叉引用。这作为一个问题经常出现,但它在该语言中不可用。

  • How to initialize struct fields which reference each other

您可以使用 Rc to work around this, perhaps in combination with RefCell.