Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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.

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