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}"); } }
你可以在此照常使用 break 和 continue。
- 在这种情况下,索引迭代在 Rust 中并不是一个特殊的语法。
(0..10)是实现Iteratortrait 的范围。step_by是返回另一个Iterator的方法,用于逐一跳过所有其他元素。- 修改矢量中的元素并说明编译器错误。将矢量
v改为可变,并将 for 循环改为for x in v.iter_mut()。