Rust Abstractions · 18 min · free with an account

Writing an Iterator

Lesson preview · about 30%

Implementing one method gives you the whole adapter library.

Core idea

Implement next(); the adapters are default methods on the trait.

Start with the idea

Iterator requires only next(); everything else — map, filter, take, zip, sum — arrives as default methods. That is why a custom sequence composes with the standard library exactly like a Vec does, without any of it knowing your type exists.

Implementing Iterator means defining the type of each item and one method, next. Each call either returns Some(item) and advances internal state or returns None when the sequence is finished. The default adapters then work automatically because they are expressed in terms of repeated next calls. That is the core composability advantage: your Fibonacci can be filtered, zipped, limited, and summed like an iterator from the standard library.

Walk through the sample with initial a and b values. Record the returned value before updating the state, then compute the pair for the next call. Test the first six outputs by hand.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Ownership Mastery