Rust 条件语句
if 是表达式、if let、match 的穷尽性检查。
if 是表达式
fn main() {
let n = 7;
if n % 2 == 0 {
println!("偶数");
} else if n % 3 == 0 {
println!("能被 3 整除");
} else {
println!("其他");
}
// 作为表达式赋值
let label = if n > 5 { "大" } else { "小" };
println!("{}", label);
}其他
大No parentheses, but braces are required. As an expression all branches must share a type and else is mandatory — otherwise there is no value when the condition fails.
match
fn main() {
let n = 3;
match n {
1 => println!("一"),
2 | 3 => println!("二或三"),
4..=9 => println!("四到九"),
_ => println!("其他"),
}
}二或三// match 也能返回值
let desc = match n {
0 => "零",
1..=9 => "个位数",
_ => "多位数",
};
println!("{}", desc);个位数穷尽性检查
enum Color {
Red,
Green,
Blue,
}
fn name(c: Color) -> &'static str {
match c {
Color::Red => "红",
Color::Green => "绿",
// 少写 Blue 会编译失败:
// error[E0004]: non-exhaustive patterns: `Blue` not covered
}
}match must cover everything. This is central to Rust's safety: add an enum variant and the compiler lists every place that needs handling. Invaluable during large refactors.
if let 与 let else
fn main() {
let some: Option<i32> = Some(42);
let none: Option<i32> = None;
// if let:只关心一个模式
if let Some(v) = some {
println!("有值 {}", v);
}
if let Some(v) = none {
println!("不会执行 {}", v);
} else {
println!("没有值");
}
// let else(Rust 1.65+):不匹配就提前返回
fn unwrap_or_zero(x: Option<i32>) -> i32 {
let Some(v) = x else {
return 0;
};
v * 2
}
println!("{} {}", unwrap_or_zero(some), unwrap_or_zero(none));
}有值 42
没有值
84 0let else is Rust's guard clause: on mismatch the else block runs (it must diverge — return, break, panic!); on match execution continues. Much flatter than nested if let.
while 与 while let
fn main() {
let mut n = 3;
while n > 0 {
println!("{}", n);
n -= 1;
}
// while let:一直取值直到模式不匹配
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
println!("弹出 {}", top);
}
}3
2
1
弹出 3
弹出 2
弹出 1match arms must yield one type when used as an expression. Arms returning () and diverging arms (return, panic!) can mix, but () and i32 cannot.if 是表达式
fn main() {
let n = 7;
if n % 2 == 0 {
println!("偶数");
} else if n % 3 == 0 {
println!("能被 3 整除");
} else {
println!("其他");
}
// 作为表达式赋值
let label = if n > 5 { "大" } else { "小" };
println!("{}", label);
}其他
大条件不需要括号,但花括号必须有。作为表达式时,所有分支的类型必须一致,且必须有 else——否则条件不成立时没有值可给。
match
fn main() {
let n = 3;
match n {
1 => println!("一"),
2 | 3 => println!("二或三"),
4..=9 => println!("四到九"),
_ => println!("其他"),
}
}二或三// match 也能返回值
let desc = match n {
0 => "零",
1..=9 => "个位数",
_ => "多位数",
};
println!("{}", desc);个位数穷尽性检查
enum Color {
Red,
Green,
Blue,
}
fn name(c: Color) -> &'static str {
match c {
Color::Red => "红",
Color::Green => "绿",
// 少写 Blue 会编译失败:
// error[E0004]: non-exhaustive patterns: `Blue` not covered
}
}match 必须覆盖所有可能。这是 Rust 保证安全的核心机制之一:给枚举加一个变体,编译器会把所有没处理的地方全部列出来。这在大型重构里价值极高。
if let 与 let else
fn main() {
let some: Option<i32> = Some(42);
let none: Option<i32> = None;
// if let:只关心一个模式
if let Some(v) = some {
println!("有值 {}", v);
}
if let Some(v) = none {
println!("不会执行 {}", v);
} else {
println!("没有值");
}
// let else(Rust 1.65+):不匹配就提前返回
fn unwrap_or_zero(x: Option<i32>) -> i32 {
let Some(v) = x else {
return 0;
};
v * 2
}
println!("{} {}", unwrap_or_zero(some), unwrap_or_zero(none));
}有值 42
没有值
84 0let else 是「卫语句」的 Rust 写法:模式不匹配时执行 else 块(必须发散——return、break、panic!),匹配则继续往下。它比嵌套 if let 平铺得多。
while 与 while let
fn main() {
let mut n = 3;
while n > 0 {
println!("{}", n);
n -= 1;
}
// while let:一直取值直到模式不匹配
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
println!("弹出 {}", top);
}
}3
2
1
弹出 3
弹出 2
弹出 1match 的每个分支必须返回同一种类型(当它被当表达式用时)。分支里写 println! 得到 (),写 return x 则是发散类型——两者能混用,但 () 和 i32 不能。