rust - rust future -调整作为水槽的功能

标签 rust rust-tokio

我有一个类似于tokio connect example的方法,它带有接受接收器的方法:

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;

最佳答案

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

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

Playground example

关于rust - rust future -调整作为水槽的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61140838/

相关文章:

windows - 如何根据操作系统系列具有不同的依赖关系

rust - 由于实验功能无法安装沙沙声

rust - 使用 Hyper HTTP Client 实现重试

multithreading - 如何等待 tokio 任务完成?

rust - 如果不允许在任务之间共享可变状态,为什么 Rust 有互斥量和其他同步原语?

rust - mio 负载较小的简单 TCP 服务器出现“连接被对等重置”错误

rust - 我应该如何重组图形代码以避免出现 "Cannot borrow variable as mutable more than once at a time"错误?

asynchronous - Rust 中单线程异步应用程序的高效同步原语

tcp - 在Tokio中使用TcpStream读取碎片化的TCP数据包

rust - 如何在 tokio_core::io::Codec::decode(...) 中实现零拷贝?