How to pass arguments to a thread in rust?

I have a closure which I cannot change, which I need to run in a new thread and to which I need to pass a variable. This is how I imagine the code to look like:

use std::thread;

fn main() {
    // I can not influence this closure, but this is what it looks like
    let handle = move |data: i32| {
        println!("Got {data}")
    };

    let foo = 123;
    // This doesn't work
    thread::spawn(handle).arg(foo).join()
}

Equivalent code in Python is does work so I am wondering whether this is possible in rust and if so then how.

Thank you in advance.

>Solution :

The documentation for thread::spawn() indicates it expects as input a closure with no arguments. Therefore, you can’t directly use your handle closure. However, you can create a new closure with no arguments that calls your handle closure like so:

use std::thread;

fn main() {

    let handle = move |data: i32| {
        println!("Got {data}")
    };

    let foo = 123;

    thread::spawn(move || {handle(foo)}).join();
}

Leave a Reply