Rust Abstractions · 18 min · free with an account

Iterators

Lesson preview · about 30%

Iterators compose lazy transformations before consuming results.

Core idea

Adapters are lazy; a consumer is what makes the work happen.

Start with the idea

map and filter build a description of the work; nothing runs until a consumer such as collect, sum, or a for loop asks for items. That laziness is why a long chain still makes a single pass over the data instead of one pass per step.

An iterator is a sequence of values produced on demand. Calling .filter() or .map() builds another iterator; it does not run the closure over every element immediately. A consumer such as .collect(), .sum(), or a for loop pulls values through the chain. In the example, each requested output asks the filter for the next even input, then squares that value. There is no separate vector of filtered values unless you explicitly collect one.

This laziness can save allocations and allow early stopping.

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