map is lazy


In this example we can see that during the assignment to double nothing really happened. The iterator did not iterate. Only after the first println when we iterated over the elements of double, only then we saw the output from the print-statements inside the map.


examples/vectors/map-is-lazy/src/main.rs
fn main() {
    let numbers = vec![1, 3, 6];
    let double = numbers.into_iter().map(|num| {
        println!("doubling {num}");
        num * 2
    });

    println!("Nothing happended yet");
    for num in double {
        println!("{num:?}");
    }
}

Nothing happended yet
doubling 1
2
doubling 3
6
doubling 6
12