从闭包发送通道信号



我正在尝试从闭包内发送信号,使用以下代码。

use std::thread;
use std::sync::mpsc::channel;
fn main() {
    let (tx, rx) = channel();
    let t1 = thread::spawn(move || {
        watch(|x| tx.send(x));
    });
    let t2 = thread::spawn(move || {
        println!("{:?}", rx.recv().unwrap());
    });
    let _ = t1.join();
    let _ = t2.join();
}
fn watch<F>(callback: F) where F : Fn(String) {
    callback("hello world".to_string());
}

但是,它编译失败并引发以下错误:

src/test.rs:8:19: 8:29 note: expected type `()`
src/test.rs:8:19: 8:29 note:    found type `std::result::Result<(), std::sync::mpsc::SendError<std::string::String>>`

我错过了什么吗?

您已经声明您的watch函数接收Fn(String)类型的闭包。通常闭包类型包括它的返回类型:Fn(String) -> SomeReturnTypeFn(String)相当于Fn(String) -> (),意味着闭包应该返回一个空元组()()在c语言中的用法与void类似。

但是,您试图使用的闭包(|x| tx.send(x))返回std::result::Result<(), std::sync::mpsc::SendError<std::string::String>>。您可以在Result上使用unwrap()来检查操作是否成功,并使闭包返回():

watch(|x| tx.send(x).unwrap());

或者,您可以这样声明watch函数,以便它可以接收返回任何类型的闭包:

fn watch<F, R>(callback: F)
    where F: Fn(String) -> R
{
    // ...
}

但是Result无论如何都应该检查。

最新更新