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 https://doc.rust-lang.org/src/core/iter/adapters/mod.rs.html#1038-1068

1 Like