To iterate over a vector with index in Rust, you can use the .iter().enumerate()
method, which provides both the index and the value of each element in the vector.
In this example,
num_vec
containing several numeric values using the vec!
macro.for
loop to iterate over the vector. The .iter().enumerate()
method is used to get an iterator that yields pairs of the index and reference to each element in the vector.(index, value)
. The index is of type usize
, and the value is a reference to the element in the vector.println!
macro to print both the index and the value in each iteration.fn main() {
let num_vec = vec![10, 20, 30, 40, 50];
for (index, value) in num_vec.iter().enumerate() {
println!("Index: {} Value: {}", index, value);
}
}
Index: 0 Value: 10 Index: 1 Value: 20 Index: 2 Value: 30 Index: 3 Value: 40 Index: 4 Value: 50
In this example,
str_vec
containing several string slices using the vec!
macro.for
loop to iterate over the vector. The .iter().enumerate()
method is used to get an iterator that yields pairs of the index and reference to each element in the vector.(index, value)
. The index is of type usize
, and the value is a reference to the string slice in the vector.println!
macro to print both the index and the value in each iteration.fn main() {
let str_vec = vec!["apple", "banana", "cherry", "date"];
for (index, value) in str_vec.iter().enumerate() {
println!("Index: {} Value: {}", index, value);
}
}
Index: 0 Value: apple Index: 1 Value: banana Index: 2 Value: cherry Index: 3 Value: date
In this tutorial, we learned How to Iterate Over a Vector with Index in Rust language with well detailed examples.