Position RPosition Search Indexes

Locate first and last matching indexes with position and rposition, composing parse-failing predicates via is_ok so unparseable entries are skipped.

RustData Integrity

Code

rustsnippet
18 lines
fn main() {
    let versions = vec!["1.4", "2.0", "1.4", "2.1", "1.4"];

    // search indexes: position 从头找第一个匹配的索引
    let first = versions.iter().position(|v| *v == "1.4");
    // rposition:DoubleEndedIterator 从尾找最后一个匹配
    let last = versions.iter().rposition(|v| *v == "1.4");
    println!("first 1.4 at {:?}, last 1.4 at {:?}", first, last);

    // 谓词可以带解析:parse 失败的元素被 is_ok 过滤掉
    let numeric = vec!["12", "x9", "30", "zz"];
    let first_parseable = numeric.iter().position(|s| s.parse::<i32>().is_ok());
    println!("first parseable index: {:?}", first_parseable);

    // 无匹配时两个方法都返回 None,调用方必须处理缺失
    let missing = versions.iter().position(|v| v.starts_with('3'));
    println!("missing probe: {:?}", missing);
}

How the snippet works

Everything happens inside the function main.

Watch out for

  • Nothing arrives from a registry; the language ships every API used.

Using it

The primary signature is fn main()

Output lines are prefixed (first 1.4 at, first parseable index:, missing probe:), making each step’s effect easy to spot.

Key statements

let first_parseable = numeric.iter().position(|s| s.parse::<i32>().is_ok());
let missing = versions.iter().position(|v| v.starts_with('3'));
let first = versions.iter().position(|v| *v == "1.4");

Interactive Tools for This Topic

FAQ

What does Position RPosition Search Indexes print when run?
Run it as a complete program — the output lines carry labels such as `first 1.4 at`, `first parseable index:`, `missing probe:`.