【发布时间】:2021-08-04 15:14:33
【问题描述】:
我正在尝试创建一个节点结构,但我不知道为什么它不会编译 (Rust playground):
trait SomeTrait {}
struct SomeObject<'a> {
something: &'a dyn SomeTrait,
}
impl<'a> SomeTrait for SomeObject<'a> {}
struct OtherObject {}
impl SomeTrait for OtherObject {}
pub struct Node {
children: Vec<Box<dyn SomeTrait>>,
}
fn main() {
let a = vec![OtherObject {}];
let b: Vec<Box<dyn SomeTrait>> = a
.iter()
.map(|d| Box::new(SomeObject { something: d }) as Box<dyn SomeTrait>)
.collect();
//But if i comment this it's fine... why?
Box::new(Node { children: b });
}
error[E0597]: `a` does not live long enough
--> src/main.rs:17:38
|
17 | let b: Vec<Box<dyn SomeTrait>> = a
| ^ borrowed value does not live long enough
18 | .iter()
19 | .map(|d| Box::new(SomeObject { something: d }) as Box<dyn SomeTrait>)
| ----------------------------------------------------------- returning this value requires that `a` is borrowed for `'static`
...
24 | }
| - `a` dropped here while still borrowed
为什么说a仍在使用?其他变量之前不应该去掉吗?
【问题讨论】:
标签: rust lifetime borrow-checker trait-objects