kvarn_async::prelude::compact_str::core

Module iter

1.6.0 · source
Expand description

Composable external iteration.

If you’ve found yourself with a collection of some kind, and needed to perform an operation on the elements of said collection, you’ll quickly run into ‘iterators’. Iterators are heavily used in idiomatic Rust code, so it’s worth becoming familiar with them.

Before explaining more, let’s talk about how this module is structured:

§Organization

This module is largely organized by type:

  • Traits are the core portion: these traits define what kind of iterators exist and what you can do with them. The methods of these traits are worth putting some extra study time into.
  • Functions provide some helpful ways to create some basic iterators.
  • Structs are often the return types of the various methods on this module’s traits. You’ll usually want to look at the method that creates the struct, rather than the struct itself. For more detail about why, see ‘Implementing Iterator’.

That’s it! Let’s dig into iterators.

§Iterator

The heart and soul of this module is the Iterator trait. The core of Iterator looks like this:

trait Iterator {
    type Item;
    fn next(&mut self) -> Option<Self::Item>;
}

An iterator has a method, next, which when called, returns an Option<Item>. 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. Individual iterators may choose to resume iteration, and so calling next again may or may not eventually start returning Some(Item) again at some point (for example, see TryIter).

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