0Pricing
Learn Rust Coding · Lesson

Custom Iterators

Implement Iterator.

Make Your Own Iterator

You are not limited to built-in iterators. By implementing the Iterator trait on your own type, it gains every adapter and consumer for free.

All you must provide is the Item type and a next method.

A Counter Struct

Start with a struct that holds the iterator's state. A simple counter just needs a current value.

struct Counter {
    count: u32,
}

fn main() {
    let c = Counter { count: 0 };
    println!("start at {}", c.count);
}

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