Example. 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.
Step 1 We call iter() and then position with a lambda expression to find the first element matching the value 20.
Step 2 When no element in the slice matches the condition, the value None is returned. With is_none() we can test for None.
Step 3 We can use other expressions as the argument to position, such as a greater than or equals expression.
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
Rposition. 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
Reference error. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.