find the index of an element in an array in rust

To find the index of an element in an array in Rust, you can use the iter() method to create an iterator over the array and then use the position() method to find the first index where the given element is found. Here is an example code snippet:

main.rs
let arr = [10, 20, 30, 40, 50];
let element_to_find = 30;

let index = arr.iter().position(|&x| x == element_to_find);

match index {
    Some(i) => println!("Index of {}: {}", element_to_find, i),
    None => println!("{} not found in the array", element_to_find),
}
268 chars
10 lines

In this example, we have an array arr with some elements and a variable element_to_find that represents the element we want to find the index of. We use the iter() method to create an iterator over the array and then use the position() method to search for the first index where the given element is found.

The position() method returns an Option<usize>, which means it either returns Some(index) where index is the first index of the element found, or None if the element is not found in the array. We use a match statement to handle both cases and print the index or a message indicating that the element was not found in the array.

related categories

gistlibby LogSnag