To get the index of a specified item in a vector in Rust, you can use the iter()
method along with position()
or enumerate()
.
In this example,
vec
containing numeric elements.iter()
method on vec
to obtain an iterator.position()
method on the iterator to find the index of the specified item.fn main() {
let vec = vec![1, 2, 3, 4, 5];
let item = 3;
let index = vec.iter().position(|&x| x == item);
println!("{:?}", index);
}
Some(2)
In this example,
vec
containing string elements.iter()
method on vec
to obtain an iterator.enumerate()
method on the iterator to find the index of the specified item.fn main() {
let vec = vec!["apple", "banana", "cherry", "date"];
let item = "banana";
let index = vec.iter().position(|&x| x == item);
println!("{:?}", index);
}
Some(1)
In this tutorial, we learned How to get the Index of Specified Item in a Vector in Rust language with well detailed examples.