Iterator adapters
Iterator adapters are methods that wrap an iterator and change what it yields: map, filter, take, flat_map, enumerate. They are lazy and usually fuse into one pass.
Detailed Explanation
An adapter takes self (the iterator) and returns a new iterator. map transforms each item. filter drops items. take stops after n items. skip discards a prefix. flat_map maps to an iterator and flattens. enumerate pairs each item with an index. chain concatenates two iterators. zip walks two in lockstep. windows and chunks live on slices and produce subslice iterators.
Laziness means v.iter().map(expensive).filter(...) does no work. A consumer pulls: for, collect, fold, count, any, find, last. Fusion means the compiler typically turns filter().map().count() into one loop with the body inlined, not three allocations. That is why an iterator pipeline can match a handwritten loop.
Stateful adapters exist. peekable lets you look at the next item without consuming it. scan is a fold that yields intermediate states. group_by is not in std; you use chunk_by on slices (Rust 1.77+) or a crate. rev requires a DoubleEndedIterator. step_by skips.
The algorithmic choice is which adapters you compose. A filter then a take is "first n matches" and is O(n) in the worst case but stops early. A collect then a second pass is two walks and an allocation. Prefer keeping the value as an iterator until you need random access or a collection you will store.
When you reach for adapters: transforming or filtering a sequence in one pass. When you reach for a for loop: the body has early breaks, ? in a non-Try context that is clearer as a loop, or several mutating side effects that read worse as for_each. When you reach for collect mid-pipeline: you need .sort() or indexed access.
Code Examples
fn main() {
let xs = [1, 2, 3, 4, 5, 6];
let taken: Vec<_> = xs
.iter()
.copied()
.filter(|n| n % 2 == 0)
.map(|n| n * 10)
.take(2)
.collect();
println!("{taken:?}"); // prints: [20, 40]
}Common Gotchas
Forgetting a consumer does nothing
A `map` without `collect` or a loop is a dropped adapter. Watch for unused-iterator warnings.
`collect` mid-chain throws away laziness
Sort needs a collection. Filtering does not. Do not `collect` between `filter` and `map`.
Some adapters need extra traits
`rev` needs `DoubleEndedIterator`. `size_hint` helps `collect` reserve; not every adapter has a tight hint.
`cloned` versus `copied`
`copied` is for `Copy` items. `cloned` calls `Clone`. Using `cloned` on `i32` works and is the louder name.