for expressions

The for expression is closely related to the while let expression. It will automatically call into_iter() on the expression and then iterate over it:

  1. fn main() {
  2. let v = vec![10, 20, 30];
  3. for x in v {
  4. println!("x: {x}");
  5. }
  6. for i in (0..10).step_by(2) {
  7. println!("i: {i}");
  8. }
  9. }

You can use break and continue here as usual.

  • Index iteration is not a special syntax in Rust for just that case.
  • (0..10) is a range that implements an Iterator trait.
  • step_by is a method that returns another Iterator that skips every other element.
  • Modify the elements in the vector and explain the compiler errors. Change vector v to be mutable and the for loop to for x in v.iter_mut().