I'm getting an error when trying to use a closure that does exactly the same as the print
function below (in ln.9)
The error is the usual borrowed value does not live long enough
. I've tried to replicate this in the playground
but I can't. I'm certain that this is mainly because I don't really understand what's going on here so any help would be really appreciated.
What I can't understand is what is the difference between calling the print
function and calling the check
closure. They have exactly the same signature and even the same body.
How does the context in which they were created affect the borrow checker? What would be the solution to this?
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);
}
The error is:
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>>) {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^