How to find the index of an element in an array, vector or slice in Rust?
Hello! I'm new to Rust and trying to solve a simple problem: find the index of an element in an array. In other languages (e.g., Python), I'm used to methods like `list.index()`, but in Rust it's different.
Here's an example: I have an array of numbers, and I want to find the index of the number `5`.
```rust
fn main() {
let arr = [1, 3, 5, 7, 9];
let target = 5;
// How to find the index of 5?
}
```
I tried using `arr.iter().position(|x| x == target)`, but I get an error. The documentation says that `position` returns `Option`, and I don't understand how to properly handle this result. Also, I'm not sure if this works for `Vec` and slices (`&[i32]`).
Another question: what to do if the element is not found? In Python, I would get an exception, but in Rust, as I understand, I need to handle `None`. But how do I do this?
No answers yet.
Log in to leave an answer
Blogs