Answer#
thread::spawn needs a closure that is valid for the whole life of the thread, which the compiler cannot bound. A closure that merely borrows name could be running after name is freed. Ownership has to move into the thread.
use std::thread;
fn main() {
let name = String::from("Ada");
let handle = thread::spawn(|| {
println!("hello, {name}");
});
handle.join().unwrap();
}error[E0373]: closure may outlive the current function, but it borrows `name`, which is owned by the current function
--> src/main.rs:5:32
|
5 | let handle = thread::spawn(|| {
| ^^ may outlive borrowed value `name`
6 | println!("hello, {name}");
| ---- `name` is borrowed here
|
note: function requires argument type to outlive `'static`
--> src/main.rs:5:18
|
5 | let handle = thread::spawn(|| {
| __________________^
6 | | println!("hello, {name}");
7 | | });
| |______^
help: to force the closure to take ownership of `name` (and any other referenced variables), use the `move` keyword
|
5 | let handle = thread::spawn(move || {
| ++++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0373`.The answers below are the valid ways out.