简体   繁体   中英

How can I return a JoinHandle from a function?

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");
    })
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM