0PricingLogin
Learn Rust Coding · Lesson

The Iterator Trait

next and laziness.

What Is an Iterator?

An iterator is anything that produces a sequence of values, one at a time. In Rust, iterators are the idiomatic way to process collections like vectors, ranges, and slices.

The whole concept is built on a single trait: Iterator. Once a type implements it, you get dozens of useful methods for free.

The Iterator Trait

The Iterator trait has one required method, next, and one associated type, Item:

  • type Item — the kind of value produced
  • fn next(&mut self) -> Option<Self::Item> — returns the next value

It returns Some(value) while values remain, then None when finished.

fn main() {
    let v = vec![10, 20, 30];
    let mut it = v.iter();
    println!("{:?}", it.next());
    println!("{:?}", it.next());
    println!("{:?}", it.next());
    println!("{:?}", it.next());
}

All lessons in this course

  1. The Iterator Trait
  2. map, filter, collect
  3. Adapters and Consumers
  4. Custom Iterators
← Back to Learn Rust Coding