rust - 有问题的借款发生在哪里?

标签 rust lifetime borrowing

pub struct Dest<'a> {
    pub data: Option<&'a i32>,
}

pub struct Src<'a> {
    pub data: Option<&'a i32>,
}

pub trait Flowable<'a: 'b, 'b> {
    fn flow(&'a self, dest: &mut Dest<'b>);
}

impl<'a: 'b, 'b> Flowable<'a, 'b> for Src<'a> {
    fn flow(&self, dest: &mut Dest<'b>) {
        dest.data = self.data;
    }
}

struct ContTrait<'a, 'b> {
    pub list: Vec<Box<Flowable<'a, 'b> + 'a>>,
}

impl<'a: 'b, 'b> Flowable<'a, 'b> for ContTrait<'a, 'b> {
    fn flow(&'a self, dest: &mut Dest<'b>) {
        for flowable in self.list.iter() {
            flowable.flow(dest);
        }
    }
}

fn main() {
    let x1 = 15;
    let x2 = 20;
    let mut c = ContTrait { list: Vec::new() };

    let mut dest = Dest { data: Some(&x2) };
    c.list.push(Box::new(Src { data: Some(&x1) }));
    c.flow(&mut dest);
}

我正在努力实现将引用从一个结构传递到另一个结构。每当我进步一点点,就会出现一个新的区 block 。我想要实现的目标在 C++ 等语言中看起来微不足道,对于 Src 类型,如果满足某些条件,则定义 Flowable 特征,A 中的引用将传递给 Dest 类型。为了让 Rust 编译器满意,我已经玩了一段时间的生命周期说明符。现在我还为 ContTrait 类型实现相同的特征,它是 Flowable 的集合,并且此 ContTrait 还实现了 Flowable 特征来迭代其中的每个对象并调用流程。这是现实世界使用的简化案例。

我就是不明白为什么 Rust 编译器会报告

error[E0597]: `c` does not live long enough
  --> src\main.rs:38:5
   |
38 |   c.flow(&mut dest);
   |   ^ borrowed value does not live long enough
39 | }
   | -
   | |
   | `c` dropped here while still borrowed
   | borrow might be used here, when `c` is dropped and runs the destructor for type `ContTrait<'_, '_>

最佳答案

pub trait Flowable<'a: 'b, 'b> {
    fn flow(&'a self, dest: &mut Dest<'b>);
}

这里的&'a self是问题的核心。它表示调用的对象 flow 必须比 dest 参数化的生命周期长。

main中,你会这样做

c.flow(&mut dest);

dest通过x2的生​​命周期隐式参数化。由于您在 c 上调用 flow,因此意味着 c 必须比 x2 更长寿,但事实并非如此。

如果您删除特征定义中 self 引用上的 'a 绑定(bind)和 ContTrait impl,则代码将编译。

关于rust - 有问题的借款发生在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53778257/

相关文章:

reference - 包含可变切片的结构

rust - 在结构中初始化函数指针

linux - 如何找到我的 Rust 项目的哪一部分使用 GLIBC 2.18

rust - Rust 中的值是如何返回的?

rust - 由于类型不匹配错误,文本文件解析函数无法编译

Rust:我可以通过以简单的方式在较小的范围内借用整个固定大小的数组来获得固定大小的切片吗

rust - 赋予调用者对彼此依赖的局部变量的所有权

rust - 生命周期不会延长,但只有当结构中有一个特征对象时

rust - 自定义并发映射结构上的“借用”借用问题

rust - 我可以从不可变的 BTreeMap 中获取值吗?