How it works...

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.

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, which makes it an infinite iterator [31].

Our SquaredVec, on the other hand, is more of a collection than an algorithm. In lines [37] to [53], we wrap the minimum of the Vec interface — we can create a SquaredVec, and we can fill it. Our type constraints Mul + Copy mean that the item the user wants to store has to be able to be copied and to be multiplied. We need this in order to square it, but it's not relevant for the iterator. T::Output is just the type that a multiplication would return, which most of the time is going to be T itself.

We could implement the Iterator trait again, but there's an easier option that will provide you with even more methods. We can allow our struct to be implicitly convertible into a slice [T], which will not only implement Iterator for you, but also a whole bunch of other methods. Because Vec implements it already, you can just return it like that [67]. If your underlying collection didn't provide a slice conversion, you could still go the same way as before and implement the Iterator trait manually.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.136.17.12