简体   繁体   English

如何从函数返回JoinHandle?

[英]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 : 我想我可以使用类似这样的东西,但我不知道该对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: 我看到thread::spawn使用此函数返回,但是我不知道这是否可以帮助我或如何使用它:

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 : 查看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 . 这表示spawn具有通用类型F This type must implement the trait FnOnce . 此类型必须实现特征FnOnce That implementation takes no arguments and returns an argument of type T . 该实现不接受任何参数,并返回类型T的参数。 spawn returns a JoinHandle that is parameterized with the same type T . spawn返回一个用相同类型T参数化的JoinHandle

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. 知道这一点后,便应使用JoinHandle进行参数化。

Your example closure calls println! 您的示例闭包调用println! which has a return type of () , so that is what this JoinHandle would use. 返回类型为() ,因此JoinHandle将使用类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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