How to Find the Index of an Element in a Vector in Rust

Created
Modified

Using position Method

The position() method searches for an element in an iterator, returning its index.

position() is short-circuiting; in other words, it will stop processing as soon as it finds a true.

See the following example:

fn main() {
  let a = ["a", "b", "c"];

  let i = a.iter().position(|&x| x == "b");
  println!("{:?}", i);

  // None
  let i = a.iter().position(|&x| x == "d");
  println!("{:?}", i);
}
Some(1)
None

Stopping at the first true:

fn main() {
  let a = [1, 2, 3, 4];

  let i = a.iter().position(|&x| x >= 2);
  println!("{:?}", i);
}
Some(1)

Related Tags