9951 explained code solutions for 126 technologies


rustHow to loop iterator in Rust


Looping over an iterator in Rust is done using the for loop. This loop will iterate over each element in the iterator and execute the code block within the loop.

let v = vec![1, 2, 3];

for i in v {
    println!("{}", i);
}

Output example

1
2
3

The code above creates a vector v with three elements and then iterates over each element in the vector using the for loop. The code block within the loop prints out the value of the element.

Code explanation

  • let v = vec![1, 2, 3];: creates a vector v with three elements
  • for i in v {: starts the for loop, which will iterate over each element in the vector v
  • println!("{}", i);: prints out the value of the element
  • }: ends the for loop

Helpful links

Edit this code on GitHub