我是 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)
}
通过编译这段代码我得到:
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
有人可以向我解释一下为什么在这种情况下a
活得不够长?在我看来,它将贯穿程序的整个生命周期。
默认情况下,Box<dyn Foo>
means Box<dyn Foo + 'static>
,所以只有'static
值可以存储在Box<dyn Foo>
. a
是在函数内部创建的,因此它不会存在'static
.
您可以使用生命周期参数来调整生命周期:
fn call<'a>(b: &Box<dyn Foo + 'a>) {
b.foo();
}
()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)