Rust futures — adapting a function as a Sink

那年仲夏 提交于 2021-02-08 11:15:17

问题


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?

eg. something like:

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

回答1:


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(())
});

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.

Playground example



来源:https://stackoverflow.com/questions/61140838/rust-futures-adapting-a-function-as-a-sink

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!