struct
, rather than the struct
itself. For more detail about why,
see ‘Implementing Iterator’.Iterator
trait. The core of
Iterator
looks like this:
next
, which when called, returns an
Option. Calling next
will return Some(Item)
as long as
there are elements, and once they’ve all been exhausted, will return None
to
indicate that iteration is finished.
Iterator
’s full definition includes a number of other methods as well,
but they are default methods, built on top of next
, and so you get
them for free.
Iterators are also composable, and it’s common to chain them together to do
more complex forms of processing. See the Adapters section
below for more details.
into_iter()
, which iterates over T
.struct
to
hold the iterator’s state, and then implementing Iterator
for that struct
.
This is why there are so many struct
s in this module: there is one for
each iterator and iterator adapter.
Let’s make an iterator named Counter
which counts from 1
to 5
:
into_iter()
on the value. Then, we match on the iterator
that returns, calling next
over and over until we see a None
. At
that point, we break
out of the loop, and we’re done iterating.
There’s one more subtle bit here: the core library contains an
interesting implementation of IntoIterator
:
Iterator
s implement IntoIterator
, by just
returning themselves. This means two things:
Iterator
, you can use it with a for
loop.IntoIterator
for it
will allow your collection to be used with the for
loop.Iterator
and return another Iterator
are
often called ‘iterator adapters’, as they’re a form of the ‘adapter
pattern’.
Common iterators adapters include map
, enumerate
and zip
.
next
. This is sometimes a source of confusion when
creating an iterator solely for its side effects. For example, the map
method calls a closure on each element it iterates over:
adapters | — |
traits | — |
zip | Converts the arguments to iterators and zips them. See the documentation of Iterator::zip for more… |
PeekableTrait | — |
Extend | Extend a collection with the contents of an iterator. Iterators produce a series of values, and collections can also be thought of as a series of values. The Extend … |
FromIterator | Conversion from an Iterator . By implementing FromIterator for a type, you define how it will be… |
IntoIterator | Conversion into an Iterator . By implementing IntoIterator for a type, you define how it will be… |
Iterator | A trait for dealing with iterators. This is the main iterator trait. For more about the concept of iterators generally, please see the module-level documentation… |