Topic
Iterators
An iterator moves through a collection one at a time. Learn how to use map, filter, and collect to process data without writing loops.
Quick Reference
ConceptWhat it means
IteratorA value that produces a sequence of items one at a time.
.iter()Borrows each element of a collection. The original collection stays usable.
.into_iter()Takes ownership of each element. The original collection is consumed.
.map(|x| ...)Transforms each item using a closure. Returns a new iterator.
.filter(|x| ...)Keeps only items where the closure returns true. Returns a new iterator.
.sum()Adds all items together and returns the total. Consumes the iterator.
.collect()Gathers all items from an iterator into a collection like a Vec. Consumes the iterator.
LazyIterators do nothing until you call a consuming method like .sum() or .collect().
TermWhat it meansWhen you use it
IteratorA value that produces items one at a time from a collection.Whenever you want to process a collection without writing a manual index loop.
.iter()Creates an iterator that borrows each element. The original collection stays usable after.When you want to read through a collection and keep the original intact.
.into_iter()Creates an iterator that takes ownership of each element. The original collection is consumed.When you want to move items out of a collection one at a time.
.map()Applies a closure to every element and returns a new iterator with the transformed values.When you want to transform every item in a collection into something else.
.filter()Keeps only the items where the closure returns true and returns a new iterator.When you want a subset of a collection based on a condition.
.sum()Adds all items and returns the total. Consumes the iterator.When you want the total of a numeric collection.
.collect()Gathers iterator items into a Vec or other collection. Consumes the iterator.After chaining adapters like map or filter, when you want a concrete collection back.
LazyIterators do no work until a consuming method is called.Every iterator chain. Nothing runs until .sum(), .collect(), or similar is invoked.