Rust 有三种循环:loop、while 和 for
fn main() {
println!("Hello, world!");
// 使用 loop 重复执行代码
// loop {
// println!("again!");
// }
// let mut counter = 0;
// let result = loop {
// counter += 1;
// if counter == 10 {
// break counter * 2;
// }
// };
// println!("The result is {result}");
let mut count = 0;
// 标签 counting_up
'counting_up: loop {
println!("count = {count}");
let mut remaining = 10;
loop {
println!("remaining = {remaining}");
if remaining == 9 {
// 没有指定标签的 break 将只退出内层循环
break;
}
if count == 2 {
// break 'counting_up; 语句将退出外层循环
break 'counting_up;
}
remaining -= 1;
}
count += 1;
}
println!("End count = {count}");
let mut number = 3;
while number != 0 {
println!("{number}!");
number -= 1;
}
println!("LIFTOFF!!!");
let a = [10, 20, 30, 40, 50];
let mut index = 0;
while index < 5 {
println!("the value is: {}", a[index]);
index += 1;
}
let a = [10, 20, 30, 40, 50];
for element in a {
println!("the value is: {}", element);
}
// Range 标准库提供的类型,用来生成从一个数字开始到另一个数字之前结束的所有数字的序列 rev 用来反转
for number in (1..4).rev() {
println!("the value is: {}", number);
}
println!("LIFTOFF!!!");
}