我是 Rust 新手,我对借用检查器的行为感到非常困惑。
trait Foo {
fn foo(&self);
}
struct Bar<'a> {
pub f : &'a Vec<i32>
}
impl<'a> Foo for Bar<'a> {
fn foo(&self) {
for i in self.f {
println!("{}", i);
}
}
}
fn call(b : &Box<dyn Foo>) {
b.foo();
}
fn main() {
let a = vec!(1,2,3);
let b : Box<dyn Foo> = Box::new(Bar {f : &a});
call(&b)
}
Run Code Online (Sandbox Code Playgroud)
通过编译这段代码我得到:
error[E0597]: `a` does not live long enough
--> main.rs:23:44
|
23 | let b : Box<dyn Foo> = Box::new(Bar {f : &a});
| ------------------^^--
| | |
| | borrowed value does not live long enough
| cast requires that `a` is borrowed for `'static`
24 | call(&b)
25 | }
| - `a` dropped here while still borrowed
Run Code Online (Sandbox Code Playgroud)
有人可以向我解释为什么在这种情况下a活得不够长吗?在我看来,它将贯穿程序的整个生命周期。
默认情况下,Box<dyn Foo>表示Box<dyn Foo + 'static>,因此只能'static将值存储在 中Box<dyn Foo>。 a是在函数内部创建的,因此它不存在于'static.
您可以使用生命周期参数来调整生命周期:
fn call<'a>(b: &Box<dyn Foo + 'a>) {
b.foo();
}
Run Code Online (Sandbox Code Playgroud)
(游乐场)
| 归档时间: |
|
| 查看次数: |
954 次 |
| 最近记录: |