Rust futures——将函数调整为Sink



我有一个类似于tokio连接示例的方法,它接受一个接收器:

pub async fn connect(
addr: &SocketAddr,
mut stdin: impl Stream<Item = Result<Request, io::Error>> + Unpin,
mut stdout: impl Sink<Response, Error = io::Error> + Unpin,
) -> Result<(), Box<dyn Error>> {

是否有一种标准/简单的方法将功能调整为水槽以进行打印和/或转换?

例如。类似于:

connect(.., .., sink::from_function(|r| match r {
Ok(response) => println!("received a response: {:?}", response),
Err(e) => println!("error! {:?}", e);
})
.await;

您可以使用与.with()方法(映射接收器的输入(链接的drain()函数(创建一个只丢弃所有项目的接收器(从函数创建接收器:

use futures::prelude::*;
use futures::sink::drain;
let sink = drain().with(|value| async move { // <-- note async block
// do something with the input...
// then return a result
Ok(())
});

您也可以使用.with()来检查或转换现有流,您只需要确保从闭包返回的成功类型与正在转换的流的输入相同。

游乐场示例

最新更新