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.

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