这个错误很常见 borrowed value does not live long enough 。我尝试在中复制这个 playground 错误,但做不到。我确信这主要是因为我不太明白这里发生了什么,所以任何帮助都会非常感谢。
函数和调用 print 有什么区别 check 。它们具有完全相同的签名,甚至相同的主体。
它们被创建的环境如何影响借用检查器?这个问题的解决方案是什么?
extern crate typed_arena;
use typed_arena::Arena;
#[derive(Debug)]
struct AstNode<'a> {
name: &'a str,
}
fn get_ast<'a>(path: &str, arena: &'a Arena<AstNode<'a>>) -> &'a AstNode<'a> {
// ...
}
type CheckFn<'a> = dyn Fn(&'a AstNode<'a>);
fn print<'a>(root: &'a AstNode<'a>) {
println!("{:?}", root);
}
fn it_does_not_have_details_if_all_ok<'a>(file: &str, check: Box<CheckFn<'a>>) {
let arena = Arena::new();
let a = &arena;
let root = get_ast(file, a);
println!("{:?}", root);
// Works
print(root);
// Produces an error
check(root);
}
错误是:
error[E0597]: `arena` does not live long enough
--> src/main.rs:21:14
|
21 | let a = &arena;
| ^^^^^ borrowed value does not live long enough
...
28 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the function body at 19:1...
--> src/main.rs:19:1
|
19 | fn it_does_not_have_details_if_all_ok<'a>(file: &str, check: Box<CheckFn<'a>>) {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^