Futures-rs: Bad experience with `StreamExt::collect` because of trait requirements

Created on 23 Nov 2019  路  3Comments  路  Source: rust-lang/futures-rs

Today collect has a requirement of Default + Extend<Self::Item>, and while I can understand why this might be a reasonable design, from a what traits should it require perspective. It just doesn't mesh well with currently established Rust design.

A very common use case of collect in normal iterator code is when you have an iterator of Result<a,err> and after collecting you want Result<Vec<a>,err>. However Default is not implemented for Result and neither is Extend. Making collect basically a useless function, for all but very trivial cases.

I don't know if it's possible as I understand it's slightly different constraints for the stream, but it just feels like something that should be possible.

Most helpful comment

Collecting into a Result<Collection<_>, _> specifically can be done via try_collect.

It could be possible to add a trait like FromStream as an equivalent to FromIterator to use instead of Default + Extend, but that would want to involve async fn-in-traits, which is not possible today (you can see that async-std::stream::FromStream forces boxing of the future and isn't Send, which would be unacceptable long term.

All 3 comments

Collecting into a Result<Collection<_>, _> specifically can be done via try_collect.

It could be possible to add a trait like FromStream as an equivalent to FromIterator to use instead of Default + Extend, but that would want to involve async fn-in-traits, which is not possible today (you can see that async-std::stream::FromStream forces boxing of the future and isn't Send, which would be unacceptable long term.

functions like collect are also just for the simple cases. There are more advanced versions for the more advanced cases. The more advanced version of collect is fold. You specify the initial value and how elements are added yourself.

Yes that's fair I was not aware of the try_collect however it also seems like it's more inline with Rust philosophy than collect from the std lib.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

seanmonstar picture seanmonstar  路  4Comments

sile picture sile  路  5Comments

critiqjo picture critiqjo  路  3Comments

flying-sheep picture flying-sheep  路  3Comments

jimblandy picture jimblandy  路  5Comments