if
语法与其他语言基本一致。
在let语句中使用if:
let condition = true;
let num = if condition {5} else {6};
let num2 = if condition {5} else {"str"}; // 报错,变量必须只有一个类型loop
必须通过break退出。
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2; // break 可以返回值
}
};
println!("The result is {result}");
}循环标签
在多层循环中,可以在循坏上指定循环标签,这样在break或continue时,就可以指定作用的循环。
fn main() {
let mut count = 0;
'counting_up: loop {
println!("count = {count}");
let mut remaining = 10;
loop {
println!("remaining = {remaining}");
if remaining == 9 {
break; // 退出内层循环
}
if count == 2 {
break 'counting_up; // 退出外层循环
}
remaining -= 1;
}
count += 1;
}
println!("End count = {count}");
}while
与其他语言相同。
for
和Python类似。