# ?-like early return on iterator error

**URL:** <https://users.rust-lang.org/t/like-early-return-on-iterator-error/27589>\
**Category:** help\
**Created:** [April 24, 2019, 8:29pm UTC](https://users.rust-lang.org/t/like-early-return-on-iterator-error/27589 "2019-04-24T20:29:43Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![zslayton](https://avatars.discourse-cdn.com/v4/letter/z/4bbf92/32.png) [@zslayton](https://users.rust-lang.org/u/zslayton)\
**Post date:** [April 24, 2019, 8:29pm UTC](https://users.rust-lang.org/t/like-early-return-on-iterator-error/27589/1 "2019-04-24T20:29:43Z")

</div>

I'm trying to design a simple API for iterating over values retrieved from a file. I'd like to point my users to [`std::Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html) and be done with it. Unfortunately (but correctly!), my iterator's `Item` type is `io::Result<u64>`, so I need to deal with the possibility of an `Err` at each step. I don't want the code to panic and I'd like to stop processing as soon as an `Err` is encountered.

What I'm after is something like this:

```rust
let answer: Result<u64, io::Error> = input
  .iter()
  .take(10)
  .sum();

```

In many contexts I can use the `?` operator to short-circuit processing when an `Err` variant of `Result` is encountered, but there doesn't seem to be an equivalent for working with `Iterator`.

I'm aware of [`filter_map()`](https://doc.rust-lang.org/rust-by-example/error/iter_result.html#ignore-the-failed-items-with-filter_map), but I don't want to ignore failures.

I'm aware of [`partition()`](https://doc.rust-lang.org/rust-by-example/error/iter_result.html#collect-all-valid-values-and-failures-with-partition), but the input could be quite long. I don't want to continue pulling from the iterator after the first `Err` is returned.

I'm aware of [`collect()`](https://doc.rust-lang.org/rust-by-example/error/iter_result.html#fail-the-entire-operation-with-collect), but users will only very rarely want to `collect()` the values they're reading. It's much more likely that they'll want to process them as they go, avoiding allocation.

I'm aware of [`try_fold()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.try_fold) and [`try_for_each()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.try_for_each), but these won't allow me to use the `Iterator` API -- I'll have to fully define the processing for each individual value within a lambda. At that rate, I may as well use a for loop instead of an iterator.

Is anyone aware of a way to short-circuit iterators?

Thanks!

---

<div class="post-metadata">

**Author:** ![cuviper](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/cuviper/32/3156_2.png) [@cuviper](https://users.rust-lang.org/u/cuviper)\
**Post date:** [April 24, 2019, 8:43pm UTC](https://users.rust-lang.org/t/like-early-return-on-iterator-error/27589/2 "2019-04-24T20:43:03Z")

</div>

> [@zslayton](#):
>
> What I’m after is something like this:
> 
> ```rust
> let answer: Result<u64, io::Error> = input
> .iter()
> .take(10)
> .sum();
> 
> ```

This should just work, because `Result` implements `Sum`:

> **[Result in std::result - Rust](https://doc.rust-lang.org/std/result/enum.Result.html#impl-Sum%3CResult%3CU%2C%20E%3E%3E)**
>
> \`Result\` is a type that represents either success (\`Ok\`) or failure (\`Err\`).

---

<div class="post-metadata">

**Author:** ![zslayton](https://avatars.discourse-cdn.com/v4/letter/z/4bbf92/32.png) [@zslayton](https://users.rust-lang.org/u/zslayton)\
**Post date:** [April 24, 2019, 10:01pm UTC](https://users.rust-lang.org/t/like-early-return-on-iterator-error/27589/3 "2019-04-24T22:01:58Z")

</div>

Huh! Good eye, that's an interesting observation. While `sum()` works, however, I believe the larger question about short-circuiting still stands.

```rust
let index: Result<Option<bool>, io::Error> = input
  .iter() // We should be able to end iteration if this returns Err
  .position(|id| id == 7); // This returns Option<bool>

```

I suspect this is not possible without a new language feature (or alternative iterator trait).

---

<div class="post-metadata">

**Author:** ![cuviper](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/cuviper/32/3156_2.png) [@cuviper](https://users.rust-lang.org/u/cuviper)\
**Post date:** [April 24, 2019, 10:14pm UTC](https://users.rust-lang.org/t/like-early-return-on-iterator-error/27589/4 "2019-04-24T22:14:07Z")

</div>

True, you can't unwrap arbitrary `Iterator` methods this way. I'll bet you can almost always approximate this with other methods, especially `try_fold`, but you're right it won't be as nice as the `?` operator.

---

<div class="post-metadata">

**Author:** ![zslayton](https://avatars.discourse-cdn.com/v4/letter/z/4bbf92/32.png) [@zslayton](https://users.rust-lang.org/u/zslayton)\
**Post date:** [April 25, 2019, 12:26am UTC](https://users.rust-lang.org/t/like-early-return-on-iterator-error/27589/5 "2019-04-25T00:26:52Z")

</div>

I just found @sfackler's [`fallible-iterator`](https://docs.rs/crate/fallible-iterator/0.2.1) crate, which appears to offer a version of the `Iterator` trait that does exactly this! I'll have to try it out, curious to know whether there's any performance overhead.

---

<div class="post-metadata">

**Author:** ![samuelpilz](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/samuelpilz/32/33384_2.png) [@samuelpilz](https://users.rust-lang.org/u/samuelpilz)\
**Post date:** [April 25, 2019, 7:09pm UTC](https://users.rust-lang.org/t/like-early-return-on-iterator-error/27589/6 "2019-04-25T19:09:50Z")

</div>

I want a `try_collect`. Is using the failing iterators really the best option? Or should I use `try_fold`? Is there any reason the Standard library does not provide failing collection?

---

<div class="post-metadata">

**Author:** ![cuviper](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/cuviper/32/3156_2.png) [@cuviper](https://users.rust-lang.org/u/cuviper)\
**Post date:** [April 25, 2019, 7:19pm UTC](https://users.rust-lang.org/t/like-early-return-on-iterator-error/27589/7 "2019-04-25T19:19:22Z")

</div>

> [@samuelpilz](#):
>
> I want a `try_collect` .

Collecting to `Result<C, E>` or `Option<C>` should work fine for this.

---

<div class="post-metadata">

**Author:** ![samuelpilz](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/samuelpilz/32/33384_2.png) [@samuelpilz](https://users.rust-lang.org/u/samuelpilz)\
**Post date:** [April 25, 2019, 7:53pm UTC](https://users.rust-lang.org/t/like-early-return-on-iterator-error/27589/8 "2019-04-25T19:53:02Z")

</div>

🤦‍♂️ I have asked this question in this forum already a few months ago...

---

<div class="post-metadata">

**Author:** ![dcarosone](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/dcarosone/32/10360_2.png) [@dcarosone](https://users.rust-lang.org/u/dcarosone)\
**Post date:** [April 26, 2019, 2:37am UTC](https://users.rust-lang.org/t/like-early-return-on-iterator-error/27589/9 "2019-04-26T02:37:38Z")

</div>

You can use:

- `Iterator::flatten()`, to treat an inner `Err` like a `None`, taking advantage of `impl<T, E> IntoIterator for Result<T, E>`
- `Iterator::fuse()` to stop at errors

---

<div class="post-metadata">

**Author:** ![samuelpilz](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/samuelpilz/32/33384_2.png) [@samuelpilz](https://users.rust-lang.org/u/samuelpilz)\
**Post date:** [April 26, 2019, 6:10pm UTC](https://users.rust-lang.org/t/like-early-return-on-iterator-error/27589/10 "2019-04-26T18:10:02Z")

</div>

But this hides the error and does not propagate it

---

<div class="post-metadata">

**Author:** ![shepmaster](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/shepmaster/32/149_2.png) [@shepmaster](https://users.rust-lang.org/u/shepmaster)\
**Post date:** [April 26, 2019, 7:48pm UTC](https://users.rust-lang.org/t/like-early-return-on-iterator-error/27589/11 "2019-04-26T19:48:10Z")

</div>

Itertools' [`process_results`](https://docs.rs/itertools/0.8.0/itertools/fn.process_results.html) may be what you want. In fact, its first version is what is in the standard library to implement `sum` for `Result`.

```rust
fn example(input: impl Iterator<Item = Result<u64, io::Error>>) -> Result<Option<u64>, io::Error> {
    itertools::process_results(input, |input| input.max())
}

```

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [July 25, 2019, 7:48pm UTC](https://users.rust-lang.org/t/like-early-return-on-iterator-error/27589/12 "2019-07-25T19:48:13Z")

</div>

Closed on July 25, 2019, 7:48pm UTC

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