[Pre-RFC]: Generator integration with for loops

I’m wary of a pattern syntax that matches the unwrapping/projection syntax rather than the constructing syntax like everything else (except ref, which is confusing and something we’re moving away from for precisely this reason), but I do like the idea of integrating ? into for loops somehow, since it can’t be just applied to the iterator like with other patterns.

3 Likes

This is an interesting perspective, but wouldn't it be better if the solution worked with Iterators of Results, which are already not uncommon today?

It would also ideally work with Streams; today in the futures-await craite, #[async] for elem in stream implicitly ?s the value, which I think most people would agree is probably wrong. Changing this would make using #[async] for with streams essentially the same as an Iterator of Results.

Iterator<Item=Result<T, E>> and Generator<Yield=T, Return=Result<(), E>> have different semantics. First one can produce valid results after encountered error(s), and second will produce values until either source will be successfully exhausted or will terminate on first error, without any ability to continue iterations. I think significant amount of code uses the first variant while implying the second one (i.e. you should stop iterating on the first encountered error) and leaves it up to users to properly shortcircuit errors.

In a way your proposal is orthogonal to one in the OP, but if suggested for integration will be implemented it will probably cover a significant amount of potential use-cases for your proposal. (although I am not ready to comment about async part of your message.)

3 Likes

An iterator/stream adapter along the lines of collect::<Result<Vec<_>>() might be sufficient so we wouldn’t need a new ? language feature, though such an adapter would need to be implemented as a generator and would be most useful with something like this proposal.

It might be a crazy idea, but wouldn’t it be possible to somehow add Return associated type to Iterator trait which defaults to () and remove Generator from std completely? Merging them into one trait would simplify things IMO.

Besides that, awesome RFC

3 Likes

I wrote about it in the “unresolved questions” section. Yes, ideally I too would like to have one general Generator trait which will be aliased as Iterator with appropriate restrictions. But I am not completely sure if it’s possible to do in a backwards compatible way. One small step in this direction can be renaming of Yield associated type to Item, because AFAIK trait alias proposals do not introduce ability to rename associated types.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.