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:
Iteratordefines the sequence production vianext().IntoIteratorenables types to be used inforloops and provide iterators viainto_iter(). - Iteration Modes: Collections typically offer
iter()(yielding&T),iter_mut()(yielding&mut T), andinto_iter()(yieldingT), allowing flexible access based on borrowing and ownership needs.forloops 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 theIteratortrait allows any type to define a sequence and automatically grants access to the rich set of default adapter and consumer methods. For custom collections, implementingIntoIteratorfor the type and its references provides idiomaticforloop 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.