通用 fn、通道和线程生成

Generic fn, channel, and thread spawn

我这里有这段代码:(Playground link)

use std::thread;
use std::sync::mpsc::channel;

fn run<T: Send>(task: fn() -> T) -> T {
    let (tx, rx) = channel();
    thread::spawn(move || {
        tx.send(task());
    });
    rx.recv().unwrap()
}

fn main() {
    let task = || 1 + 2;

    let result = run(task);

    println!("{}", result);
}

但我遇到了无法解决的终生错误。

<anon>:6:5: 6:18 error: the parameter type `T` may not live long enough [E0310]
<anon>:6     thread::spawn(move || {
             ^~~~~~~~~~~~~
<anon>:6:5: 6:18 help: consider adding an explicit lifetime bound `T: 'static`...
<anon>:6:5: 6:18 note: ...so that captured variable `tx` does not outlive the enclosing closure
<anon>:6     thread::spawn(move || {
             ^~~~~~~~~~~~~
<anon>:15:22: 15:26 error: mismatched types:
 expected `fn() -> _`,
    found `[closure <anon>:13:16: 13:24]`
(expected fn pointer,
    found closure) [E0308]
<anon>:15     let result = run(task);
                               ^~~~

有什么建议吗?谢谢!

错误消息建议添加一个 'static 绑定到类型参数 T。如果这样做,它将消除第一个错误:

fn run<T: Send + 'static>(task: fn() -> T) -> T

需要 'static 绑定来保证 task 返回的值可以比 task 运行的函数更长寿。 Read more about the 'static lifetime.

第二个错误是您传递的是闭包,而 run 需要函数指针。解决此问题的一种方法是将 task 从闭包更改为 fn:

    fn task() -> u32 { 1 + 2 }

这是完整的工作代码:

use std::thread;
use std::sync::mpsc::channel;

fn run<T: Send + 'static>(task: fn() -> T) -> T {
    let (tx, rx) = channel();
    thread::spawn(move || {
        tx.send(task());
    });
    rx.recv().unwrap()
}

fn main() {
    fn task() -> u32 { 1 + 2 }
    let result = run(task);
    println!("{}", result);
}