map, filter, collect
Transform sequences.
Transforming Sequences
Three methods do most of the work in iterator pipelines: map transforms each item, filter keeps some items, and collect gathers results into a collection.
Together they replace many manual loops with short, readable chains.
map: One In, One Out
map applies a closure to every item and yields the transformed value. The number of items stays the same; only their values change.
It is lazy, so the closure runs only when the iterator is consumed.
fn main() {
let nums = vec![1, 2, 3];
let doubled: Vec<i32> = nums.iter().map(|x| x * 2).collect();
println!("{:?}", doubled);
}All lessons in this course
- The Iterator Trait
- map, filter, collect
- Adapters and Consumers
- Custom Iterators