Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading