Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 23: Iterators, the Rust Superpower

Prerequisites

You will understand

  • Lazy evaluation — nothing runs until a consumer pulls
  • Zero-cost: iterator chains compile to the same code as hand-written loops
  • Key adapters: filter, map, collect, fold

Reading time

35 min
+ 25 min exercises
Lazy Evaluation

Iterator Pipelines Do Nothing Until a Consumer Pulls

Vec filter map take collect before consumer: pipeline description only after `collect()`: values are pulled through every adapter
Zero Cost

Iterator Chain vs Hand-Written Loop

Iterator chain Manual loop Lowered result values.iter() .filter(...) .map(...) .sum() let mut acc = 0; for x in values { if x % 2 == 0 { acc += x * 2; test edi, 1 jne .next lea eax, [eax + edi*2] ZERO-COST ABSTRACTION ⚡

Readiness Check - Iterator Pipeline Reasoning

SkillLevel 0Level 1Level 2Level 3
Understand lazinessI assume each adapter runs immediatelyI know consumers trigger executionI can explain when and why work is deferredI can predict runtime behavior of complex chains confidently
Track ownership through iterationI confuse iter/iter_mut/into_iterI can name borrow vs move differencesI can select iteration mode intentionally per use caseI can refactor loops and chains without ownership regressions
Diagnose type flow in chainsI patch until compile passesI can read one adapter signature at a timeI can locate exact type mismatch stage in a long chainI can design reusable iterator-based APIs with clean bounds

Target Level 2+ before trait-heavy iterator implementation work.

Compiler Error Decoder - Iterator Chains

Error codeWhat it usually meansTypical fix direction
E0282Type inference is ambiguous (often around collect)Add target type annotation (Vec<_>, HashMap<_, _>, etc.) at collection boundary
E0599Adapter/consumer not available on current typeConfirm you are on an iterator (call iter()/into_iter() when needed)
E0382Value moved unexpectedly by ownership-taking iterationBorrow with iter() or clone intentionally if ownership must be retained

Debug chain failures by splitting the pipeline into named intermediate variables and checking each type.

Step 1 - The Problem