Iterators
Enumerate
Index and Value
enumerate pairs each item with its position, useful when building indexed output.
Program
Play the program to build a numbered report from a list of words.
enumerate.rs
Replay: real traced execution (multi-file project)
fn main() {
let words = vec!["a", "b", "c"];
let mut report = String::new();
for (i, word) in words.iter().enumerate() {
report.push_str(&format!("{i}:{word} "));
}
println!("{}", report.trim());
}
words ← ["a", "b", "c"], report ← ""
1fn main() {2 let word→ ["a", "b", "c"]s = vec!["a", "b", "c"];3 let mut repor→ ""t = String::new();4 for (i, word) in words.iter().enumerate() {println!("{}", report.trim());
6 }7 println!("{}", report.trim());8}output0:a 1:b 2:c
Follow the Pairs
wordsstarts as["a", "b", "c"].enumerateyields(0, "a"),(1, "b"), and(2, "c").- The report grows by adding
index:wordplus one space each time. trimremoves the trailing space.- The program prints
0:a 1:b 2:c. | pair | report after append | | --- | --- | |(0, "a")|0:a| |(1, "b")|0:a 1:b| |(2, "c")|0:a 1:b 2:c| | aftertrim|0:a 1:b 2:c|
enumerate
`enumerate` yields `(index, item)` pairs.
tuple binding
`for (i, word)` destructures each pair.
trim
`report.trim()` drops the trailing space.
Exercise: enumerate.rs
Reproduce 0:a 1:b 2:c, then trace how each enumerate pair adds one piece to the report.