Is there an equivalent of JavaScript's indexOf

2019-06-23 21:27发布

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.

标签: arrays rust
1条回答
ら.Afraid
2楼-- · 2019-06-23 22:23

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
查看更多
登录 后发表回答