获得“借来的价值还不够长久"尝试将盒装 dyn 特性传递给函数时出错 [英] Getting "borrowed value does not live long enough" Error While Trying to Pass a Boxed dyn Trait into a Function
问题描述
我是 Rust 的新手,我对借用检查器的行为感到非常困惑.
I'm new to rust and I get really confused by the behavior of the borrow checker.
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)
}
通过编译这段代码,我得到:
By compiling this piece of code I get:
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
的寿命不够长吗?在我看来,它将贯穿程序的整个生命周期.
Could someone explain to me why in this case a
does not live long enough? It seems to me that it will live through the entire life cycle of the program.
推荐答案
默认情况下,Box
的意思是Box
,所以'static
值只能存储在 Box
中.a
是在函数内部创建的,因此它不适用于 'static
.
By default, Box<dyn Foo>
means Box<dyn Foo + 'static>
, so only 'static
values can be stored in Box<dyn Foo>
. a
is created inside a function, so it does not live for 'static
.
您可以使用生命周期参数来调整生命周期:
You can adjust the lifetime by using a lifetime parameter:
fn call<'a>(b: &Box<dyn Foo + 'a>) {
b.foo();
}
这篇关于获得“借来的价值还不够长久"尝试将盒装 dyn 特性传递给函数时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!