ZetCode

Rust match 表达式

最后修改于 2025 年 2 月 19 日

在本文中,我们将展示如何在 Rust 中使用 match 表达式。

Match 表达式

Rust 中的 match 表达式是一个强大的控制流运算符,它允许您将一个值与一系列模式进行比较,并根据匹配的模式执行代码。它类似于其他语言中的 switch 语句,但功能更强大、更灵活。

match 表达式的语法如下:

match value {
    pattern1 => expression1,
    pattern2 => expression2,
    ...
    _ => default_expression,
}

match 表达式按顺序检查 value 与每个模式的匹配情况。如果模式匹配,则执行相应的表达式。下划线 _ 是一个捕获所有模式,它匹配任何值,类似于 switch 语句中的 default 情况。

简单示例

以下是一个使用 match 表达式的简单 Rust 示例。

main.rs
fn main() {
    let number = 3;

    match number {
        1 => println!("One"),
        2 => println!("Two"),
        3 => println!("Three"),
        _ => println!("Other"),
    }
}

该程序定义了一个变量 number,并使用 match 表达式检查其值。

match number {
    1 => println!("One"),
    2 => println!("Two"),
    3 => println!("Three"),
    _ => println!("Other"),
}

match 表达式将 number 的值与每个模式进行比较。如果值与模式匹配,则执行相应的代码块。下划线 _ 用作默认情况。

$ cargo run -q
Three

Match guards (匹配守卫)

match 分支中的 if 条件称为匹配守卫。它们允许通过为模式添加额外的条件检查来实现更复杂的匹配。

main.rs
use rand::Rng;

fn main() {

  let mut rng = rand::thread_rng();
  let r = rng.gen_range(-5..=5);

  match r {
    x if x > 0 => println!("The number {} is positive", x),
    0 => println!("The number is zero"),
    _ => println!("The number {} is negative", r),
  }
}

我们使用一个随机数生成器在 -5 到 5 的范围内生成一个随机数 r

x if x > 0 => println!("The number {} is positive", x),

此分支匹配 r 大于 0 的任何值。匹配守卫 if x > 0 确保此分支仅在 r 为正数时执行。变量 x 被绑定到 r 的值并打印出来。

0 => println!("The number is zero"),

此分支匹配特定值 0,并打印一条消息,表明该数字为零。

_ => println!("The number {} is negative", r),

此分支匹配所有其他值(即不满足先前条件的值)。下划线 _ 是一个捕获所有模式,它打印一条消息,表明该数字为负数,并使用 r 的值。

分支中的多个选项

我们可以使用 | 将多个选项组合起来。

main.rs
fn main() {

    let grades = vec!["A", "B", "C", "D", "E", "F", "FX"];

    for grade in grades {
        match grade {
            "A" | "B" | "C" | "D" | "E" | "F" => println!("passed"),
            "FX" => println!("failed"),
            _ => println!("invalid"),
        }
    }
}

使用 | 运算符,我们将 A 到 F 的分数组合到一个分支中。

$ cargo run -q
passed
passed
passed
passed
passed
passed
failed

使用枚举进行匹配

match 表达式经常与 Rust 中的枚举一起使用。枚举允许您通过列举其可能的变体来定义一个类型。

main.rs
enum Direction {
    Up,
    Down,
    Left,
    Right,
}

fn main() {
    let direction = Direction::Up;

    match direction {
        Direction::Up => println!("Going up!"),
        Direction::Down => println!("Going down!"),
        Direction::Left => println!("Going left!"),
        Direction::Right => println!("Going right!"),
    }
}

在此示例中,我们定义了一个带有四个变体的 Direction 枚举。然后,我们使用 match 表达式来处理每个变体。

match direction {
    Direction::Up => println!("Going up!"),
    Direction::Down => println!("Going down!"),
    Direction::Left => println!("Going left!"),
    Direction::Right => println!("Going right!"),
}

match 表达式检查 direction 的值,并根据变体执行相应的代码块。

$ cargo run -q
Going up!

使用 Option 进行匹配

Rust 中的 Option 类型用于表示可能包含一个值(Some)或不包含值(None)的值。match 表达式通常用于处理 Option 类型。

main.rs
fn main() {
    let some_value = Some(5);

    match some_value {
        Some(value) => println!("Got a value: {}", value),
        None => println!("Got nothing"),
    }
}

在此示例中,我们使用 match 表达式来处理 Option 类型。

match some_value {
    Some(value) => println!("Got a value: {}", value),
    None => println!("Got nothing"),
}

match 表达式检查 some_valueSome 还是 None,并执行相应的代码块。

$ cargo run -q
Got a value: 5

使用 Result 进行匹配

Rust 中的 Result 类型用于错误处理。它可以是 Ok(包含一个值)或 Err(包含一个错误)。match 表达式通常用于处理 Result 类型。

main.rs
fn main() {
    let result: Result<i32, &str> = Ok(10);

    match result {
        Ok(value) => println!("Success: {}", value),
        Err(error) => println!("Error: {}", error),
    }
}

在此示例中,我们使用 match 表达式来处理 Result 类型。

match result {
    Ok(value) => println!("Success: {}", value),
    Err(error) => println!("Error: {}", error),
}

match 表达式检查 resultOk 还是 Err,并执行相应的代码块。

$ cargo run -q
Success: 10

使用模式进行匹配

match 表达式还可以与更复杂的模式一起使用,例如范围、元组和结构体。

main.rs
fn main() {
    let pair = (0, -2);

    match pair {
        (0, y) => println!("First is 0 and y is {}", y),
        (x, 0) => println!("x is {} and second is 0", x),
        _ => println!("It doesn't matter what they are"),
    }
}

在此示例中,我们使用 match 表达式来匹配一个元组。

match pair {
    (0, y) => println!("First is 0 and y is {}", y),
    (x, 0) => println!("x is {} and second is 0", x),
    _ => println!("It doesn't matter what they are"),
}

match 表达式检查元组的值,并根据模式执行相应的代码块。

$ cargo run -q
First is 0 and y is -2

在本文中,我们探讨了 Rust 中的 match 表达式。我们已经了解了如何将其用于简单值、枚举、OptionResult 以及更复杂的模式。match 表达式是 Rust 中控制流的强大工具,它允许您以清晰简洁的方式处理不同的情况。

作者

我的名字是 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。我自 2007 年以来一直在撰写编程文章。迄今为止,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面拥有超过十年的经验。

列出 所有 Rust 教程