Abstractions in Practice · 16 min · free with an account

Iterator Pipelines

Lesson preview · about 30%

Transform lazily, then choose one consumer.

Core idea

Adapters such as map and filter describe work but do nothing until a consumer asks for values.

Start with the idea

Adapters such as map and filter describe work but do nothing until a consumer asks for values. A clear pipeline separates selection, transformation, and collection without temporary vectors.

An iterator pipeline can read like a data-processing sentence: choose items, transform each chosen item, then consume the result. The sample starts with borrowed values from an array, filters for even numbers, squares them, and sums the squares. The final answer is 20 for [1, 2, 3, 4]. The adapters are lazy; sum() repeatedly pulls the next item through the chain. No intermediate vector is required.

Look closely at references. values.iter() yields &i32, while filter passes a reference to each item into its predicate, so the closure sees an extra reference layer and the example uses **v.

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