[英]How can I return a JoinHandle from a function?
解决这种情况的最佳方法是什么:
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");
})
}
我得到错误:
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
我想我可以使用类似这样的东西,但我不知道该对T
使用什么:
fn start<T>(pre: &Prefe, t: T) -> thread::JoinHandle<T> {
thread::spawn(move || {
println!("Test spawn");
})
}
我看到thread::spawn
使用此函数返回,但是我不知道这是否可以帮助我或如何使用它:
Builder::new().spawn(f).unwrap()
这似乎可行,但我不知道这是对还是错:
fn start(pre: &Prefe) -> thread::JoinHandle<()> {
thread::spawn(move || {
println!("Test spawn");
})
}
查看thread::spawn
的函数签名:
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static,
这表示spawn
具有通用类型F
此类型必须实现特征FnOnce
。 该实现不接受任何参数,并返回类型T
的参数。 spawn
返回一个用相同类型T
参数化的JoinHandle
。
要使用此信息,您需要知道闭包返回的类型。 知道这一点后,便应使用JoinHandle
进行参数化。
您的示例闭包调用println!
返回类型为()
,因此JoinHandle
将使用此类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.