Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent of JavaScript's indexOf for Rust arrays?

Tags:

arrays

rust

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.

like image 467
user Avatar asked May 27 '16 11:05

user


1 Answers

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
like image 160
Lukas Kalbertodt Avatar answered Oct 18 '22 08:10

Lukas Kalbertodt