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++.
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.