With the code:
use std::thread;
// result of expensive calculation
#[derive(Debug)]
pub struct Foo(String);
fn main() {
let foo = Foo(String::from("expensive!"));
let p = &foo;
let q = &foo;
let handle = thread::spawn(move || {
println!("{:?} from the spawned thread!", q);
});
println!("{:?} from main thread", p);
handle.join().unwrap();
}
I get the error:
error[E0597]: `foo` does not live long enough
--> src/main.rs:10:13
|
10 | let q = &foo;
| ^^^^ borrowed value does not live long enough
11 |
12 | let handle = thread::spawn(move || {
| __________________-
13 | | println!("{:?} from the spawned thread!", q);
14 | | });
| |______- argument requires that `foo` is borrowed for `'static`
...
19 | }
| - `foo` dropped here while still borrowed
I believe that foo
lives from its declaration until after handle.join().unwrap()
.
Am I correct, and if so, how can I convince the compiler of this?