How do I find the index of an element in an array, vector or slice?

前端 未结 2 737
刺人心
刺人心 2021-02-03 17:11

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 = vec![
        \"one\".to_s         


        
相关标签:
2条回答
  • 2021-02-03 17:23

    I think you should look at the position method instead.

    fn main() {
        let test = vec!["one", "two", "three"];
        let index = test.iter().position(|&r| r == "two").unwrap();
        println!("{}", index);
    }
    

    You can test it here.

    Note that this works for any iterator, so it can be used for vectors, arrays, and slices, all of which produce iterators.

    0 讨论(0)
  • 2021-02-03 17:33

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


    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.

    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!

    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).

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

    0 讨论(0)
提交回复
热议问题