What is the best way to handle a situation like this:
use std::thread;
struct Prefe;
fn main() {
let prefe = Prefe;
start(&prefe).join();
}
fn start(pre: &Prefe) -> thread::JoinHandle {
thread::spawn(move || {
println!("Test spawn");
})
}
I get the error:
error[E0243]: wrong number of type arguments: expected 1, found 0
--> src/main.rs:11:26
|
11 | fn start(pre: &Prefe) -> thread::JoinHandle {
| ^^^^^^^^^^^^^^^^^^ expected 1 type argument
I think I could use something like this, but I do not know what to use for T
:
fn start<T>(pre: &Prefe, t: T) -> thread::JoinHandle<T> {
thread::spawn(move || {
println!("Test spawn");
})
}
I see that thread::spawn
uses this to return, but I do not know if this can help me or how to use it:
Builder::new().spawn(f).unwrap()
This seems to work, but I do not know if this is the right or wrong way:
fn start(pre: &Prefe) -> thread::JoinHandle<()> {
thread::spawn(move || {
println!("Test spawn");
})
}
A JoinHandle detaches the associated thread when it is dropped, which means that there is no longer any handle to the thread and no way to join on it. Due to platform restrictions, it is not possible to Clone this handle: the ability to join a thread is a uniquely-owned permission.
Review the function signature of thread::spawn
:
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static,
This says that spawn
takes a generic type F
. This type must implement the trait FnOnce
. That implementation takes no arguments and returns an argument of type T
. spawn
returns a JoinHandle
that is parameterized with the same type T
.
To use this information, you need to know what type your closure returns. Once you know that, that is the type that your JoinHandle
should be parameterized with.
Your example closure calls println!
which has a return type of ()
, so that is what this JoinHandle
would use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With