rust - 有问题的借用发生在哪里?
问题描述
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);
}
我正在努力实现将引用从一个结构传递到另一个结构。每次我进步一点点,就会有一个新的块。我想要实现的目标在 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
。既然你 call flow
on c
,你就暗示它c
must live x2
,它没有。
如果您'a
在 trait 定义和 impl 中删除了对自引用的限制ContTrait
,则代码将编译。
推荐阅读
- javascript - 使用带有反应和p5的构造函数,得到'无法读取未定义的属性'中风''
- go - 如何使用以私有结构为参数的函数签名
- python - 使用 python 获取其他 PC 麦克风音频输入
- gradle - Ionic 4 Leaflet Map 不适用于部署,但适用于 ionic serve --devapp
- r - 在data.table R中嵌套列表的列中保持值> = 0
- python - 芹菜中的异常处理?
- oracle - 使用 Spring Data Jpa 在 Oracle 中调用存储过程时参数的数量或类型错误
- php - PHP Mysqli 准备好的语句 select fetch_assoc 给出空结果
- python-3.x - beautifulsoup 忽略了一个空格
- c# - 更新到最新的adobe软件时如何在c#winform中使用pdf阅读器Activex控件