We glimpsed iterators in Chapter 1, Getting Started with Rust. To recap, an iterator is any ordinary type that can walk over elements of a collection type in one of three ways: via self, &self, or &mut self. They are not a new concept and mainstream language such as C++ and Python have them already though that in Rust, they can appear surprising at first due to their form as an associated type trait. Iterators are used quite frequently in idiomatic Rust code when dealing with collection types.
To understand how they work, let's look at the definition of the Iterator trait from the std::iter module:
pub trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
// other default methods omitted
}
The Iterator trait is an associated type trait which mandates the two items, to be defined for any implementing type. First is the...