FuturesUnordered containing Futures outputting different types

I cannot figure out how to add Futures with different Output types into FuturesUnordered. I'm trying to achieve this using Either.

The compilation error: no method named next found for struct futures::stream::FuturesUnordered<futures::future::Either<impl futures::Future, impl futures::Future>> in the current scope

I'm not sure why next() is not available even though Either implements Stream. How can I poll the FuturesUnordered in this code? Thank you.

FuturesUnorderes requires the elements to implement Future, not Stream.

Looks like Either also implements Future.

It implements Future when both of its inner type have the same output type.

When I explicitly write that it should use next() from StreamExt using StreamExt::next(&mut futures).await; it gives the real error:

error[E0271]: type mismatch resolving `<impl futures::Future as futures::Future>::Output == u64`
   --> src/lib.rs:9:5
    |
9   |     StreamExt::next(&mut futures).await;
    |     ^^^^^^^^^^^^^^^ expected `u8`, found `u64`
    | 
   ::: /playground/.cargo/registry/src/github.com-1ecc6299db9ec823/futures-util-0.3.6/src/stream/stream/mod.rs:228:15
    |
228 |         Self: Unpin,
    |               ----- required by this bound in `futures::StreamExt::next`
    |
    = note: required because of the requirements on the impl of `futures::Future` for `futures::future::Either<impl futures::Future, impl futures::Future>`
    = note: required because of the requirements on the impl of `futures::Stream` for `futures::stream::FuturesUnordered<futures::future::Either<impl futures::Future, impl futures::Future>>`

error[E0271]: type mismatch resolving `<impl futures::Future as futures::Future>::Output == u64`
 --> src/lib.rs:9:5
  |
9 |     StreamExt::next(&mut futures).await;
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u8`, found `u64`
  |
  = note: required because of the requirements on the impl of `futures::Future` for `futures::future::Either<impl futures::Future, impl futures::Future>`

error: aborting due to 2 previous errors

Either doesn't implement Future as the left and right branch don't return the same type.

1 Like

I got it. In order to keep the types the same, I used a trait.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a0186405d82a2464b1d1a654b86a25f9

You actually might not need a trait; instead use an enum.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=e071ea574bc9b0499ddb9d90cbe4a51a

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.