fn main() {
let name = String::from("worker");
let h = std::thread::spawn(|| println!("{}", name));
h.join().unwrap();
}What happens when this is compiled?
- aIt compiles and prints
workeronce the spawned thread gets scheduled - bIt compiles, but may print an empty string, since
namecan be dropped before the thread runs - cE0373: the closure may outlive
mainyet borrowsname, andmoveis required✓ - dE0382:
nameis moved into the closure and then used again byjoin
Explanation:
thread::spawn requires a 'static closure: the new thread might run after main's stack frame is gone, so the closure cannot hold a borrow of a local. The compiler reports E0373 and suggests move ||, which transfers ownership of name into the closure. There is no runtime path here at all; the program never builds.