find index of vector item in rust

You can find the index of an item in a vector using the iter().position() method. Here's an example:

main.rs
let my_vec = vec![1, 2, 3, 4, 5];
let item_to_find = &3;

match my_vec.iter().position(|&x| x == *item_to_find) {
    Some(index) => println!("Index of item {}: {}", item_to_find, index),
    None => println!("Item {} not found in vector", item_to_find),
}
257 chars
8 lines

The iter() method returns an iterator over the vector, and position() finds the first item in the iterator that matches the given closure. In this case, the closure matches the item to find with x == *item_to_find.

If the item is found, the Some(index) branch of the match statement is executed, which prints the index found. Otherwise, the None branch is executed, which prints an error message saying the item was not found.

related categories

gistlibby LogSnag