如何在数组、向量或切片中找到元素的索引? [英] How do I find the index of an element in an array, vector or slice?

查看:49
本文介绍了如何在数组、向量或切片中找到元素的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在字符串向量中找到一个元素的索引.这是我目前得到的:

I need to find an index of an element in a vector of strings. This is what I got so far:

fn main() {
    let test: Vec<String> = vec![
        "one".to_string(),
        "two".to_string(),
        "three".to_string(),
        "four".to_string(),
    ];

    let index: i32 = test
        .iter()
        .enumerate()
        .find(|&r| r.1.to_string() == "two".to_string())
        .unwrap()
        .0;
}

它产生一个错误:

error[E0308]: mismatched types
  --> src/main.rs:9:22
   |
9  |       let index: i32 = test
   |  ______________________^
10 | |         .iter()
11 | |         .enumerate()
12 | |         .find(|&r| r.1.to_string() == "two".to_string())
13 | |         .unwrap()
14 | |         .0;
   | |__________^ expected i32, found usize

我认为这是因为 enumerate() 返回一个 (usize, _) 元组(如果我错了请纠正我),但是我如何转换 usizei32 在这里?如果有更好的方法,我愿意接受建议.

I assume that's because enumerate() returns a tuple of (usize, _) (correct me if I'm wrong), but how do I convert usize to i32 here? If there is a better approach, I'm open to suggestions.

推荐答案

TLDR 使用带有 position 方法的迭代器,Rust 文档 展示了一个很好的例子.

TLDR Use an iterator with the position method, the Rust docs shows a good example.

不,这是因为索引是usize,而不是i32.事实上,i32 完全不适合这个目的;它可能不够大,也没有理由签署.只需使用 usize.

No, it's because indices are usize, not i32. In fact, i32 is completely inappropriate for this purpose; it may not be large enough, and there's no reason for it to be signed. Just use usize.

其他一些注意事项:调用to_string() 不是免费的,你不需要它进行比较;你可以比较字符串切片就好了!

Some other notes: calling to_string() is not free, and you don't need it for the comparison; you can compare string slices just fine!

此外,如果您真的想将 usize 转换为 i32,您可以使用强制转换:x作为 i32,尽管这 不会在溢出或下溢时产生错误(结果可能为负).

Also, if you really want to turn a usize into an i32, you can do that with a cast: x as i32, though this will not produce an error on over- or under-flow (i.e. the result may be negative).

所有这一切,如 Mathieu David 的回答所述,有一个 position 方法在迭代器上做你想做的事.

All that said, as noted in Mathieu David's answer, there's a position method on iterators that does what you want.

这篇关于如何在数组、向量或切片中找到元素的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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