0PricingLogin
Learn Rust Coding · Lesson

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

  1. The Iterator Trait
  2. map, filter, collect
  3. Adapters and Consumers
  4. Custom Iterators
← Back to Learn Rust Coding