Home
Rust
position Example (iter)
This page was last reviewed on Nov 22, 2023.
Dot Net Perls
Position. 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.
iter
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.
find
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.
Option
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 22, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.