'Is there an equivalent of JavaScript's indexOf for Rust arrays?
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var index = fruits.indexOf("Apple");
let fruits = ["Banana", "Orange", "Apple", "Mango"];
let index = fruits.???
If there is no equivalent, maybe you can point me in the right direction? I found this example, but it's for vectors, not arrays.
Solution 1:[1]
You can use the method position
on any iterator. You can get an iterator over an array with the iter()
method. Try it like this:
let fruits = ["Banana", "Orange", "Apple", "Mango"];
let res1 = fruits.iter().position(|&s| s == "Apple");
let res2 = fruits.iter().position(|&s| s == "Peter");
println!("{:?}", res1); // outputs: Some(2)
println!("{:?}", res2); // outputs: None
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Lukas Kalbertodt |