HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustMajor

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
indexhowthecurrentforelementrustloopget

Problem

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 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.

Solution

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

Context

Stack Overflow Q#66288515, score: 99

Revisions (0)

No revisions yet.