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());
}
  1. 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() {
  2. println!("{}", report.trim());

    6    }7    println!("{}", report.trim());8}
    output0:a 1:b 2:c

Follow the Pairs

  1. words starts as ["a", "b", "c"].
  2. enumerate yields (0, "a"), (1, "b"), and (2, "c").
  3. The report grows by adding index:word plus one space each time.
  4. trim removes the trailing space.
  5. 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 | | after trim | 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.