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.
Code
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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.