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

标签 rust borrow-checker

以下代码无法编译:

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 中是不可能的:不支持结构成员之间的交叉引用。这经常作为一个问题出现,但它在该语言中不可用。

您可以使用 Rc解决这个问题,也许结合 RefCell .

关于rust - 引用盒装值的生命周期不够长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45319021/

相关文章:

rust - 是否可以对 Cargo.toml 中的外部代码应用补丁?

rust - 为什么不能在同一结构中存储值和对该值的引用?

filesystems - 如何在 rust-fuse 中获取 UID 和 GID?

rust - 我如何初始化一个数组,以便 Rust 知道它是一个 `String` s 而不是 `str` 的数组?

date - 如何使用 Chrono crate 在 Rust 中获取当前工作日?

rust - 借用检查器没有意识到 `clear` 丢弃了对局部变量的引用

Rust 零复制生命周期处理

linux - 带有依赖加密的错误Selenium Wire Linux

multithreading - 如何将 JoinHandle 存储在与自身运行的线程的结构中?

rust - 将集合移出上下文