Skip to content

Replace Extend in Stream::collect with custom FromStream (a la FromIterator) #1833

Open
@mehcode

Description

@mehcode

I'm puzzled on this one. I could understand Rust not being able to infer the type with how generic Stream::collect is but Rust can somehow infer it from the declaration if the type is not Copy.

use futures::executor::block_on;
use futures::future::ready;
use futures::stream::once;
use futures::Stream;
use futures::StreamExt;

fn defaults_stream<T: Default>() -> impl Stream<Item = T> {
    once(ready(T::default()))
}

fn defaults_iter<T: Default>() -> impl Iterator<Item = T> {
    vec![T::default()].into_iter()
}

fn main() {
    // iter / String : ok
    let _: Vec<String> = defaults_iter().collect();

    // iter / u32 : ok
    let _: Vec<u32> = defaults_iter().collect();

    // stream / String : ok
    let _: Vec<String> = block_on(defaults_stream().collect());

    // stream / u32 : err (?)
    let _: Vec<u32> = block_on(defaults_stream().collect());

    // stream / (u32, String) : ok (?)
    let _: Vec<(u32, String)> = block_on(defaults_stream().collect());

    // stream / (u32, u32) : err (?)
    let _: Vec<(u32, u32)> = block_on(defaults_stream().collect());
}

Any idea what's going on here?

I should note that I've tried and reproduced this in 1.36.0 and nightly 2019-08-28.


Update: After talking this through with a colleague we figured out that the issue here is that .collect() in Stream depends on Extend which has two possible implementations for Copy types on Vec.

Possible solution is to make a FromStream trait like Iterator has FromIterator.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-streamArea: futures::streamC-feature-requestS-needs-api-designStatus: Before implementing this, a discussion or decision on the new API is needed.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions