In our little example here, we are going to look at two different uses for an iterator:
- fibonacci(), which returns an infinite range of the Fibonacci sequence
- SquaredVec, which implements a (very) small subset of a Vec with a twist: it squares all items
The Fibonacci sequence is defined as a series of numbers, starting from 0 and 1, where the next number is the sum of the last two. It starts like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.
The first two are 0 and 1 per definition. The next one is their sum — 0 + 1 = 1. After that comes 1 + 1 = 2. Then 2 + 1 = 3. 3 + 2 = 5. Repeat ad infinitum.
The first two are 0 and 1 per definition. The next one is their sum — 0 + 1 = 1. After that comes 1 + 1 = 2. Then 2 + 1 = 3. 3 + 2 = 5. Repeat ad infinitum.
An algorithm can be turned into an iterator by implementing the Iterator trait. This is pretty simple, as it only expects you to provide the type you're iterating over and a single method, next, which fetches the next item. If the iterator doesn't have any items left, it should return None, otherwise Some. Our Fibonacci iterator always returns Some item...