Fallible iterators?

One thing I am missing more and more in the Rust ecosystem is a set of iterators that can handle Result and Option elements. Or rather, what I need is to make decisions based on the Some/Ok-ness of those elements. For example, stop processing when an element yields a None or an Err, and then return the error.

As far as I know, currently often the best way to handle situations like this is to largely avoid the Iterator methods (e.g. map, filter) altogether in favor of for-loops. The problems with this are

  1. that it is verbose to do (it's not just the for-loop but also the error handling code) and
  2. that it often requires an intermediate allocation.

Does anyone know of a crate that can help with this e.g. by reducing boilerplate and preventing the allocation?

2 Likes

I've used these combinators a few times.

1 Like

Any idea in what crate those combinators live? :slight_smile:

They don't live in any crate. That's why the playpen has the full source for them.

Well the ones defined on Iterator in stdlib don't cover handling Option and Result at all. They just leave an option open to do it yourself with the downsides mentioned before.

What I'm looking for is a crate that allows me to not deal with those downsides.

Hmm, seems like your code is useful, since it fills exactly OPs use case.. would you be interested in cargo publishing it? Or maybe a pull request for itertools?

1 Like

I also didn't immediately notice it was a link, but that's on me for custom-theming the rust forums and then forgetting to make hyperlinks an easily recognizable color.

Having looked at them: these iterators look pretty nice, so I agree with the suggestion @juleskers made about adding them to either itertools or another crate. If it's at all feasible for you, I encourage you to do so.

1 Like

Rust 1.27 stabilized try_fold and try_for_each on Iterator. Those may serve your needs.

2 Likes

I believe ideally this problem should be solved with generators:

2 Likes

iterr. I had to pick a license, and dig up a Travis config, and write documentation, and everything. I hope you're happy. :stuck_out_tongue:

11 Likes

What do the hip young ones say again these days? "sorrynotsorry"? :stuck_out_tongue_winking_eye:

Seriously though, thanks for sharing! I hope the resulting good karma in your future will be worth it! :heart:

2 Likes

In fact I am. Thank you for taking the time to do this :grinning:

1 Like