Skip to content
Justice Tech School

Iterators

Iterators are lazy. map, filter and take adapt them and collect, sum or count consume them.

Example
fn main() {
    let v = vec![1, 2, 3, 4, 5, 6];
    let r: Vec<i32> = v.iter().filter(|x| *x % 2 == 0).map(|x| x * x).collect();
    println!("{:?} {}", r, v.iter().sum::<i32>());
}

Result

[4, 16, 36] 21

Exercise

Consume into a Vec.

.::<Vec<_>>()

Quiz Test

Are iterator adapters lazy?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.