是否有等效于JavaScript的Rust数组的indexOf? [英] Is there an equivalent of JavaScript's indexOf for Rust arrays?

查看:283
本文介绍了是否有等效于JavaScript的Rust数组的indexOf?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

推荐答案

您可以使用方法 position 在任何迭代器上。您可以使用 iter() 方法。像这样尝试:

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

这篇关于是否有等效于JavaScript的Rust数组的indexOf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆