What’s wrong with the following code?
fn main() {
let a = 1;
let handler = std::thread::spawn(||{
dbg!(&a+1);
});
dbg!(&a);
handler.join().unwrap();
}
It’s clear that the spawned thread doesn’t outlive the main function, so why does it happen? Type system limitation?
>Solution :
Compiler is not smart enough for that, use scope():
fn main() {
let a = 1;
std::thread::scope(|s| {
s.spawn(|| {
dbg!(&a + 1);
});
});
dbg!(&a);
}