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
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());
}
enumerate
`enumerate` yields `(index, item)` pairs.
tuple binding
`for (i, word)` destructures each pair.
trim
`report.trim()` drops the trailing space.