13.8 Summary

Rust’s iterators are a fundamental and highly effective feature, promoting safe, efficient, and expressive code for processing sequences and traversable structures.

  • Core Traits: Iterator defines the sequence production via next(). IntoIterator enables types to be used in for loops and provide iterators via into_iter().
  • Iteration Modes: Collections typically offer iter() (yielding &T), iter_mut() (yielding &mut T), and into_iter() (yielding T), allowing flexible access based on borrowing and ownership needs. for loops implicitly use the appropriate mode.
  • Adapters & Consumers: Adapters (map, filter, zip, etc.) are lazy, chainable transformations returning new iterators. Consumers (collect, sum, for_each, find, etc.) are eager methods that drive the iteration to produce a result or side effect, consuming the iterator in the process.
  • Custom Iterators: Implementing the required next() method for the Iterator trait allows any type to define a sequence and automatically grants access to the rich set of default adapter and consumer methods. For custom collections, implementing IntoIterator for the type and its references provides idiomatic for loop integration. Leveraging standard library iterators (e.g., for internal arrays/slices) via delegation can significantly reduce boilerplate.
  • Zero-Cost Abstraction: Rust’s compiler optimizations (monomorphization, inlining, LLVM backend) ensure that iterator chains generally perform on par with equivalent handwritten C-style loops, providing high-level abstraction without sacrificing speed.
  • Versatility: Iterators are powerful tools for more than just linear collections; they effectively handle I/O streams, generators, and complex data structure traversals (like trees and graphs).

For programmers migrating from C, embracing Rust’s iterators is crucial for writing idiomatic and effective Rust code. They offer a robust, declarative approach to handling data sequences, shifting focus from manual index/pointer management to the high-level logic of data transformation, all while benefiting from Rust’s strong safety guarantees and impressive performance.