Post #3951952
2026-07-20 04:34 UTC
Today I was surprised that rust's Iterator::collect() can transform an Iterator> into a Result.
That is, given an iterator where each item can be either a value or an error, it can give you a result that is either a collection of values if the iterator never yielded an error, or the first error encountered by the iteration.
Figuring out how this worked let me into Result's implementation of FromIterator, which itself led me into core::iter::adapters::try_process, which bottomed out in Try, ControlFlow and Residual, which are the internal implementation of the `?` operator and `break`/`continue` in loop-like constructs, at which point my head exploded because I just cannot keep all the layers of generics and traits and magic straight to figure out where the fuck the magical thing happens.
I think the deep-ish magic for the transformation I care about is in try_process and its helper type GenericShunt, but for the life of me I cannot grok why GenericShunt does the right thing. And yet it's the only place in which the right thing can take place.
Replies (1)
-
@danderson@hachyderm.io 2026-07-20 04:36
I started down this adventure because I had an Iterator>, and I wanted a Result>. So I thought "well I guess I'll try the thing that definitely won't work and just do `foo.iter().collect()`, but that'll make a Vec>"... And then it compiled fine and gave me the thing I wanted, so I was intrigued and wanted to find out why. One headache later, I kind-of regret asking.