for 循环

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

fn main() {
    let v = vec![10, 20, 30];

    for x in v {
        println!("x: {x}");
    }
    
    for i in (0..10).step_by(2) {
        println!("i: {i}");
    }
}

你可以在此照常使用 breakcontinue

  • 在这种情况下,索引迭代在 Rust 中并不是一个特殊的语法。
  • (0..10) 是实现 Iterator trait 的范围。
  • step_by 是返回另一个 Iterator 的方法,用于逐一跳过所有其他元素。
  • 修改矢量中的元素并说明编译器错误。将矢量 v 改为可变,并将 for 循环改为 for x in v.iter_mut()