本文介绍了 Rust 的流程控制语句(if
、for
、while
、loop
)及其应用,并讲解了 match
和 if let
模式匹配的用法。
流程控制是编写程序时的重要组成部分,它决定了程序的执行逻辑。Rust 提供了多种流程控制语句,包括 if
表达式、for
循环、while
循环和 loop
循环。合理使用这些结构可以使代码更加清晰、高效。
Rust 的 if
语句不仅可以用于条件判断,还可以作为表达式返回值:
fn main() {
let number = 8;
if number % 2 == 0 {
println!("{} 是偶数", number);
} else {
println!("{} 是奇数", number);
}
let is_even = if number % 2 == 0 { "Yes" } else { "No" };
println!("Is {} even? {}", number, is_even);
}
for
语句通常用于遍历集合,并且比 while
更安全(避免数组越界)。
fn main() {
let numbers = vec![10, 20, 30, 40, 50];
for (index, value) in numbers.iter().enumerate() {
println!("索引 {}: 值 {}", index, value);
}
}
while
语句在满足条件时执行循环,但可能会导致索引越界错误。
fn main() {
let numbers = [3, 6, 9, 12, 15];
let mut index = 0;
while index < numbers.len() {
println!("数组元素: {}", numbers[index]);
index += 1;
}
}
loop
适用于需要手动 break
退出的情况,可以结合 break
作为表达式返回值。
fn main() {
let mut count = 0;
let result = loop {
count += 1;
if count == 7 {
break count * 2;
}
};
println!("Loop 计算结果: {}", result);
}
在 for
循环中,可以使用 continue
跳过本次迭代,break
终止循环。
fn main() {
for num in 1..=5 {
if num == 3 {
println!("跳过 {}", num);
continue;
}
if num == 5 {
println!("中断循环");
break;
}
println!("当前数字: {}", num);
}
}
Rust 的 match
语法允许对变量进行模式匹配,并执行相应的操作。
match
语句必须覆盖所有可能情况,因此 _
用于匹配未列出的情况。
fn main() {
let day = "Monday";
match day {
"Monday" => println!("新的一周开始了!"),
"Friday" => println!("周五快乐!"),
_ => println!("只是普通的一天"),
}
}
在 match
语句中,我们可以解构结构体并提取值。
struct Point {
x: i32,
y: i32,
}
fn main() {
let point = Point { x: 5, y: -3 };
match point {
Point { x: 0, y: 0 } => println!("原点"),
Point { x, y } if y > 0 => println!("({},{}) 位于上半平面", x, y),
Point { x, y } => println!("点的坐标: ({},{})", x, y),
}
}
枚举类型可以通过 match
进行解构匹配。
enum TrafficLight {
Red,
Yellow,
Green,
}
fn traffic_light_action(light: TrafficLight) {
match light {
TrafficLight::Red => println!("请停车!"),
TrafficLight::Yellow => println!("准备起步!"),
TrafficLight::Green => println!("可以通行!"),
}
}
fn main() {
let light = TrafficLight::Green;
traffic_light_action(light);
}
当只关心特定匹配时,可以使用 if let
进行简化。
fn main() {
let some_value = Some(42);
if let Some(x) = some_value {
println!("匹配到的值: {}", x);
}
}
if
语句可以作为表达式返回值。for
循环更安全,避免了索引错误。while
适用于基于条件的循环,但可能有越界风险。loop
适用于无限循环,并可结合 break
返回值。match
语句可以匹配结构体、枚举等,必须穷举所有可能情况。if let
适用于只匹配某个特定值的情况,使代码更简洁。如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!