How does for loop returning work?

fn main()
{
    let ani = vec!["Something", "ssdsads"];

    for (idex, a) in ani.iter().enumerate()
    {
        println!("Val: {}\tPos: {}", a, idex);
    }
}

So how does it return ani.iter().enumerate() values? Shouldn't ani.iter().enumerate() only returnt he current index I am in? How does it return the current position I am in and the value inside ani?

The doc says:

fn enumerate(self) -> Enumerate<Self>

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

The iterator returned yields pairs (i, val) , where i is the current index of iteration and val is the value returned by the iterator.

enumerate() keeps its count as a usize . If you want to count by a different sized integer, the zip function provides similar functionality.

You can look up the implementation for it here mod.rs - source

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.