#iterator #fallible

no-std fallible-iterator

Fallible iterator traits

8 releases

0.2.1 Dec 10, 2018
0.1.6 Dec 10, 2018
0.1.5 Jul 16, 2018
0.1.4 Dec 25, 2017
0.1.1 May 20, 2016

#19 in Algorithms

Download history 1677/week @ 2018-10-11 2221/week @ 2018-10-18 2053/week @ 2018-10-25 1825/week @ 2018-11-01 2297/week @ 2018-11-08 2987/week @ 2018-11-15 2874/week @ 2018-11-22 2517/week @ 2018-11-29 2349/week @ 2018-12-06 4353/week @ 2018-12-13 3706/week @ 2018-12-20 1545/week @ 2018-12-27 1248/week @ 2019-01-03

10,751 downloads per month
Used in 84 crates (19 directly)


1.5K SLoC




"Fallible" iterators for Rust.


If the std or alloc features are enabled, this crate provides implementations for Box, Vec, BTreeMap, and BTreeSet. If the std feature is enabled, this crate additionally provides implementations for HashMap and HashSet.

If the std feature is disabled, this crate does not depend on libstd.


"Fallible" iterators.

The iterator APIs in the Rust standard library do not support iteration that can fail in a first class manner. These iterators are typically modeled as iterating over Result<T, E> values; for example, the Lines iterator returns io::Result<String>s. When simply iterating over these types, the value being iterated over must be unwrapped in some way before it can be used:

for line in reader.lines() {
    let line = try!(line);
    // work with line

In addition, many of the additional methods on the Iterator trait will not behave properly in the presence of errors when working with these kinds of iterators. For example, if one wanted to count the number of lines of text in a Reader, this might be a way to go about it:

let count = reader.lines().count();

This will return the proper value when the reader operates successfully, but if it encounters an IO error, the result will either be slightly higher than expected if the error is transient, or it may run forever if the error is returned repeatedly!

In contrast, a fallible iterator is built around the concept that a call to next can fail. The trait has an additional Error associated type in addition to the Item type, and next returns Result<Option<Self::Item>, Self::Error> rather than Option<Self::Item>. Methods like count return Results as well.

This does mean that fallible iterators are incompatible with Rust's for loop syntax, but while let loops offer a similar level of ergonomics:

while let Some(item) = try!(iter.next()) {
    // work with item

No runtime deps