Alex Garella
7th November 2023
Rust offers several collection types. Common among these are arrays, vectors, and slices. Let's explore how to find the index of an element within these collections.
For arrays and slices, Rust provides the iter()
method combined with the position()
function:
fn main() {
let array = ["apple", "banana", "cherry"];
if let Some(index) = array.iter().position(|&r| r == "banana") {
println!("Index of 'banana': {}", index); //Output: Index of 'banana': 1
}
}
Vectors, being dynamic arrays, use the same method:
fn main() {
let vector = vec!["apple", "banana", "cherry"];
if let Some(index) = vector.iter().position(|&r| r == "banana") {
println!("Index of 'banana': {}", index); //Output: Index of 'banana': 1
}
}
The position()
function returns an Option<usize>
, which is Some(index)
if the element is found, or None
if it's not.
Whether you're working with fixed-size arrays, slices, or dynamic vectors, Rust's standard library provides the tools you need to find element indices safely and efficiently. Happy coding!