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

Why can't std::thread::spawn accept arguments in Rust?

In C++, we can write code like the following

void f1(int n)
{
    
}

std::thread t(f1, 1);

However, in Rust I can only do this through a closure, and it will involve capture.

fn foo(b: i32) {

}


let bb = 1;
let t1 = std::thread::spawn(move || foo(bb));

I wonder if there are some ways that I can directly create a thread that runs foo, and pass bb as its argument directly, like in C++.

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

If there are no way to do that, is this by design? Someone says closure it sugar, however, I found it is not replaceable here?

>Solution :

I wonder if there are some ways that I can directly create a thread that runs foo, and pass bb as its argument directly, like in C++.

No. std::thread::spawn can’t accept arguments because Rust’s type system does not support variadic functions. At best you could use a variadic macro to handle it for you but that seems… a lot of work for no gain at all.

If there are no way to do that, is this by design? Someone says closure it sugar, however, I found it is not replaceable here?

The article you’re linking to says that closures are syntactic sugar for a function with an associated structure, not for whatever unspecified thing you think it is.

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