How to Find the Index of an Element in a Rust Collection

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.

Arrays and Slices

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

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.

Conclusion

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!

Subscribe to receive the latest Rust jobs in your inbox

Receive a weekly overview of Rust jobs by subscribing to our mailing list

© 2024 RustJobs.dev, All rights reserved.