tokio-rs / async-stream

Asynchronous streams for Rust using async & await notation
Other
604 stars 32 forks source link

Return a stream conditionally #88

Closed Soremwar closed 1 year ago

Soremwar commented 1 year ago
fn a() -> impl Stream<Item = Result<u8, ()>> {
    try_stream!{
        yield 1;
    }
}

fn b() -> impl Stream<Item = Result<u8, ()>> {
    try_stream!{
        yield 2;
    }
}

fn decide(a: bool) -> impl Stream<Item = Result<u8, ()>> {
    if true {
        a()
    } else {
        b()
    }
}

fn main(){
    decide(false);
}

Will complain that a and b have incompatible types: distinct uses of "impl Trait" result in different opaque types

Boxing them will make me unable to pin them going forward, so what should be the way forward here?

taiki-e commented 1 year ago

The streams returned by stream!/try_stream contain opaque types (impl trait), so they are treated as different types even if the signatures are the same.

There are a few ways to handle such cases: