map is lazy that can cause problems
- We increment the counter and that's how we get the increasing numbers next to the letters.
examples/vectors/map1/src/main.rs
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.
examples/vectors/map2/src/main.rs
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.
examples/vectors/map3/src/main.rs
// 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)