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 that can cause problems

  • We increment the counter and that's how we get the increasing numbers next to the letters.
fn main() {
    let chars = vec!['a', 'b', 'c'];
    let mut cnt = 0;
    let pairs = chars.into_iter().map(|letter| {
        cnt += 1;
        (letter, cnt)
    });
    for pair in pairs {
        println!("{pair:?}");
    }
}
('a', 1)
('b', 2)
('c', 3)
  • If we call rev before we call map then the letters will be reversed, and the numbers will be attached to the letters after the reversal.
fn main() {
    let chars = vec!['a', 'b', 'c'];
    let mut c = 0;
    let pairs = chars.into_iter().rev().map(|letter| {
        c += 1;
        (letter, c)
    });
    for pair in pairs {
        println!("{pair:?}");
    }
}
('c', 1)
('b', 2)
('a', 3)
  • If we first call map and only then rev we would expect that first the numbers are generated and then the wholething is reversed, but that's not the case.
c 3
b 2
a 1
  • Because map is lazy it will be executed only after the reversal. Just as in the previous case.
// However this is also the same
fn main() {
    let chars = vec!['a', 'b', 'c'];
    let mut c = 0;
    let pairs = chars
        .into_iter()
        .map(|letter| {
            c += 1;
            (letter, c)
        })
        .rev();
    for pair in pairs {
        println!("{pair:?}");
    }
}
('c', 1)
('b', 2)
('a', 3)