控制流
根据条件是否为运行某些代码true以及在条件为时重复运行某些代码的能力true是大多数编程语言中的基本构建块
if表达式
fn main() {
let number = 6;
if number % 4 == 0 {
println!("number is divisible by 4");
} else if number % 3 == 0 {
println!("number is divisible by 3");
} else if number % 2 == 0 {
println!("number is divisible by 2");
} else {
println!("number is not divisible by 4, 3, or 2");
}
}
if在let声明中使用
代码块的计算结果是其中的最后一个表达式,数字本身也是表达式。在这种情况下,整个if表达式的值取决于执行哪个代码块。这意味着有可能从每个臂产生的值if必须是相同的类型
fn main() {
let condition = true;
let number = if condition { 5 } else { 6 };
println!("The value of number is: {number}");
}
循环重复(loop、while、for)
- 可以使用break跳出循环,continue跳过本次循环进入下一次循环
重复代码loop
死循环(直接EMO)
fn main() {
loop {
println!("again!");
}
}
从循环返回值
break用于停止循环的表达式之后添加想要返回的值(好像return表达式)
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("The result is {result}"); // 20
}
消除多个循环之间歧义的循环标签
循环标签必须以单引号开头(反人类🤔)
fn main() {
let mut count = 0;
'counting_up: loop {
println!("count = {count}");
let mut remaining = 10;
'_inner: loop {
println!("remaining = {remaining}");
if remaining == 9 {
break;
}
if count == 2 {
break 'counting_up;
}
remaining -= 1;
}
count += 1;
}
println!("End count = {count}");
}
条件循环while
fn main() {
let mut number = 3;
while number != 0 {
println!("{number}!");
number -= 1;
}
println!("LIFTOFF!!!");
}
循环遍历集合for
fn main() {
let a = [10, 20, 30, 40, 50];
for element in a {
println!("the value is: {element}");
}
}
fn main() {
for number in (1..=4).rev() {
println!("{number}!");
}
println!("LIFTOFF!!!");
for number in (1..4).rev() {
println!("{number}!");
}
println!("LIFTOFF!!!");
}