Rust 条件语句

if 是表达式、if let、match 的穷尽性检查。

Beginner
Key Points`if` 能返回值,所以可以 `let x = if c { 1 } else { 2 };`。

if 是表达式

Rust
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);
}
Output
其他
大

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

Rust
fn main() {
    let n = 3;

    match n {
        1 => println!("一"),
        2 | 3 => println!("二或三"),
        4..=9 => println!("四到九"),
        _ => println!("其他"),
    }
}
Output
二或三
Rust
// match 也能返回值
let desc = match n {
    0 => "零",
    1..=9 => "个位数",
    _ => "多位数",
};
println!("{}", desc);
Output
个位数

穷尽性检查

Rust
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

Rust
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));
}
Output
有值 42
没有值
84 0

let 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

Rust
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);
    }
}
Output
3
2
1
弹出 3
弹出 2
弹出 1
All match arms must yield one type when used as an expression. Arms returning () and diverging arms (return, panic!) can mix, but () and i32 cannot.

Friends & Partners