“for”循环
Rust 中有三个循环关键字:while
、loop
和 for
:
while
The while
keyword works much like in other languages, executing the loop body as long as the condition is true.
fn main() { let mut x = 200; while x >= 10 { x = x / 2; } println!("Final x: {x}"); }
for
The for
loop iterates over ranges of values:
fn main() { for x in 1..5 { println!("x: {x}"); } }
loop
The loop
statement just loops forever, until a break
.
fn main() { let mut i = 0; loop { i += 1; println!("{i}"); if i > 100 { break; } } }
This slide should take about 5 minutes.
- 我们稍后会讨论迭代;暂时只使用范围表达式。
- 请注意,
for
循环只迭代到4
。现在展示使用1..=5
语法表示一个包含边界的范围。