Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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; } 

It produces an error:

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 

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.

like image 428
Caballero Avatar asked May 31 '15 13:05

Caballero


People also ask

How do I find a particular index of an element?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.

Where is the index in an array?

The index of a value in an array is that value's location within the array. There is a difference between the value and where the value is stored in an array.

Is there an R function for finding the index of an element in a vector?

Use the match() Function to Find the Index of an Element in R. The match() function is very similar to the which() function. It returns a vector with the first index (if the element is at more than one position as in our case) of the element and is considered faster than the which() function.

What is the index of an element?

Each element inside a list will have a unique position that identifies it. That position is called the element's index.


1 Answers

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.

like image 104
Mathieu David Avatar answered Sep 23 '22 19:09

Mathieu David