Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Iterators

The Iterator trait

Reference for the Rust Iterator trait: the next() method, the Item type, provided methods, size_hint, laziness, and how to implement your own iterator.

Iterator is the trait behind every for loop, every .map(...) chain and every collect(). To implement it you supply two things: an associated type Item (what the iterator yields) and a method next that returns Some(item) until the sequence ends, then None. Everything else, more than seventy methods such as map, filter, sum and zip, is provided for free on top of next.

Iterators are lazy. Building a chain of adapters does no work; items are pulled one at a time when something at the end of the chain (a for loop or a consuming method like collect) asks for them.

Rust
pub trait Iterator {
    type Item;
    fn next(&mut self) -> Option<Self::Item>;
    // ... many provided methods
}

Try it

Rust Calling next by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Implementing Iterator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
pub trait Iterator {
    type Item;
    fn next(&mut self) -> Option<Self::Item>;
    fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
    // adapters (return new iterators): map, filter, enumerate, zip, take, skip, chain, ...
    // consumers (use up the iterator): collect, sum, count, fold, last, nth, ...
}
Name Description
Item The type of each element yielded. It may be an owned value (i32), a reference (&T) or a mutable reference (&mut T).
next Advances the iterator and returns the next item, or None when it is exhausted.
size_hint Returns (lower, upper) bounds on the remaining length; upper is None if unknown. The default is (0, None). It is only a hint and must not be trusted for memory safety in safe code.

Returns (from next): Some(item) while items remain, None after the end.

Edge cases: after the first None, calling next again may return Some again for a badly behaved iterator. Only fuse() guarantees None forever.

Usage notes

  • Adapters versus consumers. Adapters (map, filter, take) return a new iterator and do nothing until driven. Consumers (collect, sum, for_each, count) pull items until the end. A chain with no consumer triggers the compiler warning unused ... that must be used.
  • next needs &mut self, so you must declare the iterator let mut it. Methods that take self by value (map, collect) consume it; use by_ref() to keep using it afterwards.
  • Implement size_hint when you can. collect and extend use the lower bound to pre-allocate. If your iterator's length is exact, also implement ExactSizeIterator.
  • Double-ended and fused behaviour are separate traits. Add DoubleEndedIterator if you can also yield from the back, which unlocks rev().
  • Collections hand out iterators through three methods: iter() (items are &T), iter_mut() (&mut T) and into_iter() (owned T). See IntoIterator.
  • Performance: iterator chains are usually compiled down to the same machine code as a hand-written loop, because every adapter is a generic struct that the optimizer inlines.
  • Infinite iterators are fine (0.., repeat, cycle) as long as you stop with take, take_while or find. A consumer like count() or collect() on one never returns.