Iterators in Rust
Table of Contents
Iterators in Rust
In Rust, iterators are a powerful and efficient way to process sequences of data. They provide a standardized, lazy, and often zero-cost abstraction for working with collections (like Vec, HashMap, String) and other sequences. Iterators are central to Rust's idiomatic style, promoting Functional Programming patterns and highly optimized code.
Core Concepts
The
IteratorTrait: The heart of Rust's iterator system is theIteratortrait, defined in the standard library. Any type that wants to be an iterator must implement this trait.pub trait Iterator { type Item; // Associated type: the type of the items produced by the iterator // The core method: attempts to return the next item. // Returns `Some(item)` if there's an item, `None` if the iteration is complete. fn next(&mut self) -> Option<Self::Item>; // Many other default methods are provided on the trait (e.g., map, filter, collect, for_each) // that use `next` internally and provide convenient transformations. }- Lazy Evaluation: Iterators in Rust are lazy. This means that calling methods like
maporfilteron an iterator does not immediately perform the operations. Instead, they return new iterators that represent the transformation. The actual work (consuming items and applying transformations) only happens when a consuming adaptor (likecollect(),for_each(),sum()) is called. This can lead to very efficient code. - Iterators vs. Collections: Iterators themselves are not data structures that hold data. They are adaptors that yield data from some source (a collection, a range, a generator, etc.) one element at a time.
- Three Ways to Get an Iterator from Collections:
iter(): Borrows each element immutably (&T).let v = vec![1, 2, 3]; let iter = v.iter(); // yields &i32
iter_mut(): Borrows each element mutably (&mut T).let mut v = vec![1, 2, 3]; let iter_mut = v.iter_mut(); // yields &mut i32
into_iter(): Consumes the collection and moves ownership of each element out (T).let v = vec![1, 2, 3]; let into_iter = v.into_iter(); // yields i32, consumes v
Iterator Adaptors (Transforming Iterators)
Iterator adaptors are methods defined on the Iterator trait that consume one iterator and produce another, transformed iterator. They are lazy.
map(): Applies a closure to each item and produces a new iterator with the results.let numbers = vec![1, 2, 3]; let doubled: Vec<i32> = numbers.iter().map(|x| x * 2).collect(); // [2, 4, 6]
filter(): Keeps only items for which a given closure returnstrue.let numbers = vec![1, 2, 3, 4, 5]; let evens: Vec<i32> = numbers.iter().filter(|&&x| x % 2 == 0).cloned().collect(); // [2, 4] // Note: filter on `&i32`, so we dereference twice `&&x` and then clone to get owned i32s.
zip(): Combines two iterators into an iterator of pairs.let a = [1, 2, 3]; let b = ['a', 'b', 'c']; for (num, char) in a.iter().zip(b.iter()) { println!("{}: {}", num, char); }flat_map(): Maps each element to an iterator, then flattens the result into a single iterator.let words = vec!["hello", "world"]; let chars: Vec<char> = words.into_iter().flat_map(|s| s.chars()).collect(); // ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
skip(),take(),peekable(),enumerate(),fold(), etc.
Consuming Adaptors (Executing the Iteration)
Consuming adaptors are methods that consume the iterator (by calling next() repeatedly) and produce a final result. They trigger the lazy evaluation.
collect(): Gathers all items from the iterator into a collection (e.g.,Vec,HashMap,String). Requires type annotation for the target collection.let s = "hello world"; let chars: Vec<char> = s.chars().collect();
for_each(): Executes a closure for each item, typically for side effects.let numbers = vec![1, 2, 3]; numbers.iter().for_each(|x| println!("{}", x));sum(): Calculates the sum of numeric items.let numbers = vec![1, 2, 3, 4]; let total: i32 = numbers.iter().sum(); // 10
count(): Returns the number of items in the iterator.max(),min(): Returns the maximum or minimum item.find(): Returns the first item that satisfies a predicate.any(),all(): Checks if any/all items satisfy a predicate.
Why Iterators Are Important in Rust
- Performance: Due to lazy evaluation and compiler optimizations (often "zero-cost abstractions"), Rust iterators can be as fast as, or even faster than, hand-written loops. The compiler can often unroll loops and optimize the chain of adaptor calls.
- Readability and Expressiveness: They promote a functional style, making code more concise and easier to understand, especially for complex data transformations.
- Safety: They integrate seamlessly with Rust's ownership and borrowing system, ensuring memory safety during iteration.
- Flexibility: Can be used with any type that implements the
Iteratortrait, leading to highly generic and reusable code. - DRY Principle: Many common looping patterns are encapsulated in highly optimized iterator methods, reducing boilerplate code.