fnmain() { letmut number = 1; letresult = loop { number += 1; if number == 10 { break number; } }; println!("result {} value {}",result ,number); }
Console
1
result 10 value 10
while
当条件为真,执行循环。当条件不再为真。调用 break 停止循环。
案例
1 2 3 4 5 6 7 8 9
fnmain() { letmut number = 3;
while number > 0 { println!("{}!", number); number = number - 1; } println!("done {} ",number); }
Console
1 2 3 4
3! 2! 1! done 0
for
遍历集合
案例一
1 2 3 4 5 6 7 8 9 10 11 12
fnmain(){ letarr = [1,2,3,4,5]; letmut index = 0; while index < 3 { println!("value {}",arr[index]); index = index + 1; } forelementin arr.iter() { println!("value is: {}", element); } }
Console
1 2 3 4 5 6 7 8
value 1 value 2 value 3 value is: 1 value is: 2 value is: 3 value is: 4 value is: 5