To get the index of a specified element in an array in Rust, you can use the iter() method and enumerate the elements.
In this example,
arr
with values 10, 20, 30, 40, 50.iter()
method on the array to get an iterator over its elements.enumerate()
method to iterate over the elements along with their indices.fn main() {
let arr = [10, 20, 30, 40, 50];
let specified_element = 30;
if let Some(index) = arr.iter().position(|&x| x == specified_element) {
println!("Index of specified element {} is: {}", specified_element, index);
} else {
println!("Specified element not found in the array");
}
}
Index of specified element 30 is: 2
In this example,
arr
with values 10, 20, 30, 40, 50.iter()
method on the array to get an iterator over its elements.enumerate()
method to iterate over the elements along with their indices.fn main() {
let arr = [10, 20, 30, 40, 50];
let specified_element = 60;
if let Some(index) = arr.iter().position(|&x| x == specified_element) {
println!("Index of specified element {} is: {}", specified_element, index);
} else {
println!("Specified element not found in the array");
}
}
Specified element not found in the array
In this tutorial, we learned How to get the Index of Specified Element in an Array in Rust language with well detailed examples.