for (i,j) in (5..10).enumerate() {println!("i = {} and j = {}", i, j);}
输出:
i = 0 and j = 5
i = 1 and j = 6
i = 2 and j = 7
i = 3 and j = 8
i = 4 and j = 9
再比如:
let lines ="Content of line oneContent of line twoContent of line threeContent of line four".lines();for (linenumber, line) in lines.enumerate() {println!("{}: {}", linenumber, line);}
输出:
0: Content of line one
1: Content of line two
2: Content of line three
3: Content of line four
关于迭代器的知识,详见 迭代器 章节。
while
Rust 提供了 while 语句,条件表达式为真时,执行语句体。当你不确定应该循环多少次时可选择 while。
while expression { code}
比如:
letmut x =5; // mut x: i32letmut done =false; // mut done: boolwhile!done { x += x -3;println!("{}", x);if x %5==0 { done =true; }}
loop
有一种情况,我们经常会遇到,就是写一个无限循环:
whiletrue {// do something}
针对这种情况,Rust 专门优化提供了一个语句 loop。
loop {// do something}
loop 与 while true 的主要区别在编译阶段的静态分析。
比如说,如下代码:
letmut a;loop { a =1;// ... break ...}do_something(a)
'outer:for x in0..10 { 'inner:for y in0..10 {if x %2==0 { continue 'outer; } // continues the loop over xif y %2==0 { continue 'inner; } // continues the loop over yprintln!("x: {}, y: {}", x, y); }}