gpt4 book ai didi

rust - 尝试将盒装 dyn 特性传递给函数时出现 "borrowed value does not live long enough"错误

转载 作者:行者123 更新时间:2023-12-03 11:28:53 24 4
gpt4 key购买 nike

我是 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>意味着 Box<dyn Foo + 'static> ,所以只有 'static值可以存储在 Box<dyn Foo> . a在函数内部创建,因此它不适用于 'static .
您可以使用生命周期参数调整生命周期:

fn call<'a>(b: &Box<dyn Foo + 'a>) {
b.foo();
}
( playground )

关于rust - 尝试将盒装 dyn 特性传递给函数时出现 "borrowed value does not live long enough"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63109103/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com