从闭包发送通道信号
Sending channel signal from a closure
我正在尝试使用以下代码从闭包内发送信号。
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)
的闭包。通常闭包类型包括其 return 类型:Fn(String) -> SomeReturnType
。 Fn(String)
等同于 Fn(String) -> ()
并且意味着你的闭包应该 return 一个空元组 ()
。 ()
的用法类似于 C 中的 void
。
但是,您尝试使用的闭包 (|x| tx.send(x)
) returns std::result::Result<(), std::sync::mpsc::SendError<std::string::String>>
代替。您可以在 Result
上使用 unwrap()
来检查操作是否成功并关闭 return ()
:
watch(|x| tx.send(x).unwrap());
或者,您可以这样声明 watch
函数,以便它可以接收闭包 returning 任何类型:
fn watch<F, R>(callback: F)
where F: Fn(String) -> R
{
// ...
}
但是 Result
无论如何都应该检查一下。
我正在尝试使用以下代码从闭包内发送信号。
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)
的闭包。通常闭包类型包括其 return 类型:Fn(String) -> SomeReturnType
。 Fn(String)
等同于 Fn(String) -> ()
并且意味着你的闭包应该 return 一个空元组 ()
。 ()
的用法类似于 C 中的 void
。
但是,您尝试使用的闭包 (|x| tx.send(x)
) returns std::result::Result<(), std::sync::mpsc::SendError<std::string::String>>
代替。您可以在 Result
上使用 unwrap()
来检查操作是否成功并关闭 return ()
:
watch(|x| tx.send(x).unwrap());
或者,您可以这样声明 watch
函数,以便它可以接收闭包 returning 任何类型:
fn watch<F, R>(callback: F)
where F: Fn(String) -> R
{
// ...
}
但是 Result
无论如何都应该检查一下。