Lifetime about using closure

I'm studying concurrency now. I wrote the below code to understand it, but an error occurs about lifetime. I do not understand this error.

use std::thread;
fn main() {
let mut handles = Vec::new();

for x in 0..10 {
    handles.push(thread::spawn(|| {
        println!("{}", x);

for handle in handles {

An error message is

closure may outlive the current function, but it borrows `x`, which is owned by the current function

In this message, what function "the current function" means? If this means fn main(), closure must be in it, so I cannot understand this error message.

thread::spawn allows that the spawned thread outlives the caller. For this reason, it requires that the passed closure has 'static as lifetime. The closure here however is borrowing the variable x, which gives it a lifetime of at most the body of the loop, as the next iteration drops the current x. The solution is to force x to be moved into the closure using move || { /* ... */ }.

Thank you. I understood it.
Does it depends on each environment that if spawned thread outlive the caller or not?

std::thread::spawn always allows the spawned thread to outlive the caller. The crossbeam and rayon crates provide so called "scoped" threads. Those can borrow values from the caller.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.