Enumerate Pairs Items With Indexes

Pair each element with its position using enumerate, add one for one-based numbering, and place it before filter to keep source indexes.

RustData Integrity

Code

rustsnippet
25 lines
fn main() {
    let stages = ["build", "test", "deploy"];

    // enumerate 产出 (索引, 元素) 对,索引随迭代自动推进
    for (index, stage) in stages.iter().enumerate() {
        println!("{index}: {stage}");
    }

    // 1-based 编号:先 enumerate,再在 map 里加一
    let numbered: Vec<String> = stages
        .iter()
        .enumerate()
        .map(|(i, s)| format!("{}. {s}", i + 1))
        .collect();
    println!("{numbered:?}");

    // 过滤后仍要原始位置:enumerate 放在 filter 之前,索引指向源序列
    let long: Vec<usize> = stages
        .iter()
        .enumerate()
        .filter(|(_, s)| s.len() > 4)
        .map(|&(i, _)| i)
        .collect();
    println!("long stage indexes: {long:?}");
}

How the snippet works

Enumerate Pairs Items With Indexes is built around the function main.

Iteration happens inside for (index, stage) in stages.iter().enumerate() — everything outside it runs once.

Applying it

The demo output is labeled (long stage indexes:), so every printed line maps back to its originating operation.

Statements that matter

for (index, stage) in stages.iter().enumerate() {
println!("{index}: {stage}");
}
.map(|(i, s)| format!("{}. {s}", i + 1))
.collect();
.filter(|(_, s)| s.len() > 4)
.map(|&(i, _)| i)
.collect();

Interactive Tools for This Topic

FAQ

What does Enumerate Pairs Items With Indexes print when run?
Invoke the file as-is — the `long stage indexes:` prefixes identify which step printed each line.