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.
pub trait Iterator { type Item; fn next(&mut self) -> Option<Self::Item>; // ... many provided methods }
Try it
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.
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
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 warningunused ... that must be used. nextneeds&mut self, so you must declare the iteratorlet mut it. Methods that takeselfby value (map,collect) consume it; useby_ref()to keep using it afterwards.- Implement
size_hintwhen you can.collectandextenduse the lower bound to pre-allocate. If your iterator's length is exact, also implementExactSizeIterator. - Double-ended and fused behaviour are separate traits. Add
DoubleEndedIteratorif you can also yield from the back, which unlocksrev(). - Collections hand out iterators through three methods:
iter()(items are&T),iter_mut()(&mut T) andinto_iter()(ownedT). SeeIntoIterator. - 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 withtake,take_whileorfind. A consumer likecount()orcollect()on one never returns.