Find All Matching Positions Enumerate

position stops at the first hit, enumerate with filter_map collects every matching index, and rposition scans the same predicate from the back.

RustData Integrity

Code

rustsnippet
28 lines
fn main() {
    let readings = [12, 7, 12, 33, 12, 5];

    // position stops at the first hit
    let first = readings.iter().position(|&v| v == 12);
    println!("first position: {first:?}");

    // collect ALL matching positions: enumerate + filter_map keeps the index
    let all: Vec<usize> = readings
        .iter()
        .enumerate()
        .filter_map(|(i, &v)| (v == 12).then_some(i))
        .collect();
    println!("all positions: {all:?}");

    // rposition runs the same search from the back
    let last = readings.iter().rposition(|&v| v == 12);
    println!("last position: {last:?}");

    // the same enumerate pattern works for any predicate
    let hot: Vec<usize> = readings
        .iter()
        .enumerate()
        .filter(|&(_, &v)| v > 10)
        .map(|(i, _)| i)
        .collect();
    println!("hot positions: {hot:?}");
}

Following the execution — Find All Matching Positions Enumerate

Structurally, expect the function main and nothing else.

What to watch for

  • No dependencies to declare — the platform runtime has the whole surface.

Using it

The one signature that matters: fn main()

The printed lines carry these labels: first position:, all positions:, last position: — when the file runs.

Key statements

let first = readings.iter().position(|&v| v == 12);
let last = readings.iter().rposition(|&v| v == 12);
.filter(|&(_, &v)| v > 10)
.map(|(i, _)| i)
.collect();

Interactive Tools for This Topic

FAQ

What does Find All Matching Positions Enumerate print when run?
The script runs standalone; its 4 labeled outputs include `first position:`, `all positions:`, `last position:`.