Iterators
An iterator is a value that produces a sequence of items by repeating next(). Adapters such as map and filter are lazy: they do nothing until something consumes the iterator.
Detailed Explanation
Iterator is a trait with one required method, next(&mut self) -> Option<Self::Item>, and dozens of default methods. None means the sequence is finished. Some(item) is the next value. for x in iter is a loop that calls next until None.
Iterators are lazy. vec.iter().map(|x| x * 2) does not multiply anything. It builds an adapter that will multiply when pulled. .collect(), .sum(), .for_each(), a for loop, or .next() are what pull. Forgetting to consume is a compile warning (unused_must_use on some adapters) or a silent no-op on others. If you expected a loop to run, look for a missing collect or for.
Three ways to iterate a collection: .iter() yields &T and leaves the collection. .iter_mut() yields &mut T. .into_iter() yields T and consumes the collection. A for loop on a Vec calls into_iter. A for loop on &Vec calls iter. That is why for x in vec moves the vector and for x in &vec does not.
Adapters come in two families. Intermediate adapters return a new iterator: map, filter, take, skip, flat_map, enumerate. Terminal adapters consume the iterator and return a value: collect, fold, sum, count, any, find. Chaining intermediate adapters fuses into one pass in typical cases. filter then map then collect walks the slice once.
You can implement Iterator for your own type. Store the state in the struct, advance it in next, return None when done. Implement IntoIterator if you want for x in my_type to work. Implement ExactSizeIterator and DoubleEndedIterator when you can, so adapters can take shortcuts.
When you reach for an iterator: almost every walk of a collection. When you reach for an index loop: you need the index for random access, or you are filling a buffer in place. Prefer iterators; they avoid off-by-one errors and extra bounds checks.
Code Examples
fn main() {
let names = ["ada", "grace", "alan"];
let upper: Vec<String> = names
.iter()
.filter(|name| name.len() > 3)
.map(|name| name.to_uppercase())
.collect();
println!("{upper:?}"); // prints: ["GRACE", "ALAN"]
let total: u32 = (1..=4).sum();
println!("{total}"); // prints: 10
}Common Gotchas
Adapters are lazy
`v.iter().map(...);` without `collect` or a loop does no work. The compiler may warn; do not ignore it.
`for x in vec` consumes `vec`
Use `&vec` or `vec.iter()` when you need the vector afterwards.
`collect` needs a target type
Write `collect::<Vec<_>>()` or annotate the binding. Inference often cannot pick between `Vec` and `HashSet`.
Do not `collect` just to iterate again
A second pass is fine when you need a collection. A `collect` between two adapters is usually a wasted allocation.