Idea: Fallible iterator mapping with `try_map`

Yeah, I've wanted this for a long time for discoverability.

Before Friday? Poorly.

But Make `array::{try_from_fn, try_map}` and `Iterator::try_find` generic over `Try` by scottmcm · Pull Request #91286 · rust-lang/rust · GitHub was just merged to fix Decide on generic-ness of functions like `Iterator::try_find` and `array::try_map` · Issue #85115 · rust-lang/rust · GitHub, which gives a way forward for this.

So like try_reduce just did, I think it could just be .try_collect::<Vec<_>>(), where the method would be fn try_collect<B>(&mut self) -> ChangeOutputType<Self::Item, B> -- and thus if the iterator's item is Option<T> the method would return Option<Vec<T>>, for an item type of Result<T, E> it'd return Result<Vec<T>, E>, and so on.

(The &mut self also helps distinguish this from collect -- you could resume using the iterator after the error, if you wanted.)

Want to make a PR? :slightly_smiling_face:

5 Likes