All lessons

Lesson 11 of 11

Iterators

Transform a sequence, keep the values you need, and collect them.

main.rs

fn main() {    let numbers = 1..=4;    let pipeline = numbers        .map(|n| n * 2)        .filter(|&n| n >= 6);    let kept: Vec<i32> = pipeline.collect();    println!("{kept:?}");}

Program state

Pipeline
Ready to build
Step 1 of 9

The program will build a pipeline that turns a range into a vector.

What’s happening

An iterator yields items one at a time. The map method transforms each item. The filter method keeps only the items whose test returns true. The little functions inside vertical bars are closures. Here |&n| reads the integer through the reference that filter supplies.

Map and filter are lazy. They describe work to do later. Calling collect pulls items through the pipeline and gathers the results in a new vector.

Read more in The Rust Book