fn main() {
let data = 20;
let c = || &data;
c();
}
The above code return a reference to a variable captured, it compiles. But after adding a move
keyword before the closure, it fails to compile.
fn main() {
let data = 20;
let c = move || &data;
c();
}
error: lifetime may not live long enough
--> src/bin/clo.rs:3:21
|
3 | let c = move || &data;
| ------- ^^^^^ returning this value requires that `'1` must outlive `'2`
| | |
| | return type of closure is &'2 i32
| lifetime `'1` represents this closure's body
|
= note: closure implements `Fn`, so references to captured variables can't escape the closure
From what i can tell, the move keyword just move captured variables to closure, when we return a refrence to the captured variable, we are actually returning a reference to one of the closure struct's field, as long as the closure is not dropped before using the returned reference, all should be fine.
So why is this not allowed? Is there any other considerations?