Closure may outlive the current function, but it borrows `foo`, which is owned by the current function

Viewed 33

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?

1 Answers

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);
}
Related