How to pass a Stream as parameter into an async trait function?

Using the impl keyword I know that it's possible to pass a Stream argument as parameter into an async non-trait function. However impl <Trait> is not possible for an argument in an async function. Anyone any idea how this could be done? Thanks.

Can you show an example that you wish compiled?

Failing example:

use async_trait::async_trait;
use tokio::*;

pub trait HookUp
    async fn bind<S>(&self) -> Box<S>
        S: futures::Stream<Item = tokio::io::Result<dyn tokio::io::AsyncRead + tokio::io::AsyncWrite>>;

The issue has nothing to do with the async trait thing. It's just that:

  1. A dyn Trait must be in a box or behind a reference.
  2. The + in dyn Trait only allows adding auto traits such as Send. You can't combine AsyncRead with AsyncWrite.

The same would apply in an ordinary function.

fn foo<S>(s: S) -> S
    S: futures::Stream<Item = Result<dyn AsyncRead + AsyncWrite>>


@alice Indeed, that's true; sorry for making it more complex than needs to. Do you have a suggesting how a Stream could be passed in this case?

(In a previous situation, following your suggestion then, I was able to split the stream in a reader and writer separately. In this case that's not possible).

You can make a custom trait for things that implement both?

Alternatively this might work for you?

use async_trait::async_trait;
use tokio::io::*;

pub trait HookUp {
    type Stream: futures::Stream<Item = Result<Self::RW>>;
    type RW: AsyncRead + AsyncWrite;

    async fn bind(&self) -> Self::Stream;

@alice That works! Thanks so much!!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.