Often in Rust we call iter()
to get an iteration over a slice of elements. We may need to find an element that matches a condition.
And with position, and rposition, we can get the first matching element's index. This gives us the ability to use the index, not just the value.
To begin we need a slice of some integers, so we declare 5 integers in a vector. Then we act upon this vector in the remainder of the program.
iter()
and then position with a lambda expression to find the first element matching the value 20.None
is returned. With is_none()
we can test for None
.fn main() { let values = vec![10, 20, 30, 40, 50]; // Step 1: compute position for a value. if let Some(twenty_position) = values.iter().position(|&x| x == 20) { println!("POSITION FOR 20: {twenty_position}"); } // Step 2: this item does not exist. if values.iter().position(|&x| x == 100).is_none() { println!("POSITION FOR 100 IS NONE"); } // Step 3: try a greater than or equal to expression. if let Some(high_value) = values.iter().position(|&x| x >= 40) { println!("POSITION FOR HIGH VALUE: {high_value}"); } }POSITION FOR 20: 1 POSITION FOR 100 IS NONE POSITION FOR HIGH VALUE: 3
Sometimes we want to begin searching from the end of the slice to the beginning. This is a rightward search, and rposition helps here.
fn main() { let values = vec!["dog", "dog"]; // Find index of rightmost dog. if let Some(rightmost) = values.iter().rposition(|&v| v == "dog") { println!("RIGHTMOST: {}", rightmost); } }RIGHTMOST: 1
In Rust we must usually use the ampersand operator on the argument to position. This fixes an error where Rust cannot compare a reference with a value.
fn main() { let values = vec![0i32]; if let Some(example) = values.iter().position(|x| x == 20) { } }error[E0277]: can't compare `&i32` with `{integer}` --> src/main.rs:3:57 ... = help: the trait `PartialEq<{integer}>` is not implemented for `&i32` = help: the trait `PartialEq` is implemented for `i32` For more information about this error, try `rustc --explain E0277`.
When we need to get the index of a matching element within a slice, the position (and rposition) functions are ideal. We must first call iter()
before using position.