Rust 期货 - 将函数调整为 Sink [英] Rust futures -- adapting a function as a Sink

查看:38
本文介绍了Rust 期货 - 将函数调整为 Sink的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似于 tokio 连接示例的内容 使用接受接收器的方法:

I have something similar to the tokio connect example with a method that accepts a sink:

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>> {

是否有一种标准/简单的方法可以使函数适应用于打印和/或转换的接收器?

Is there a standard/easy way to adapt a function to a sink for printing and/or transformation?

例如.类似:

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

推荐答案

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

You can use the drain() function (which creates a sink that just discards all items) chained with the .with() method (which maps the inputs of a sink) to create a sink from a function:

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() 来检查或转换现有的流,您只需要确保从闭包返回的成功类型与您的流的输入相同正在转型.

You can also use .with() to inspect or transform an existing stream, you just need to ensure that the success type you return from the closure is the same as the input of the stream you're transforming.

游乐场示例

这篇关于Rust 期货 - 将函数调整为 Sink的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆