How do I get the index of the current element in a for loop in Rust?

Viewed 10389

I have a for loop:

let list: &[i32]= vec!(1,3,4,17,81);


for el in list {
 println!("The current element is {}", el);
 println!("The current index is {}", i);// <- How do I get the current index?
}

How can I get the index of the current element?

I have tried

for el, i in list

for {el, i} in list

for (el, i) in list.enumerate()

I was able to access the iterator using a map of the vec, but received an error:

unused `std::iter::Map` that must be used

note: `#[warn(unused_must_use)]` on by default
note: iterators are lazy and do nothing unless consumed

, and this SO answer on the subject leads me to believe I should be using a for loop instead (though I could be misunderstanding), because I am not trying to adjust the original vec in any way.

1 Answers

Just use enumerate:

Creates an iterator which gives the current iteration count as well as the next value.

fn main() {
    let list: &[i32] = &vec![1, 3, 4, 17, 81];

    for (i, el) in list.iter().enumerate() {
        println!("The current element is {}", el);
        println!("The current index is {}", i);
    }
}

Output:

The current element is 1
The current index is 0
The current element is 3
The current index is 1
The current element is 4
The current index is 2
The current element is 17
The current index is 3
The current element is 81
The current index is 4
Related