教程 rust tutorial

模式匹配 match

Rust 的 match 是强大的控制流结构,用于匹配值并根据不同模式执行对应代码。

基本语法

rust
let number = 7;

match number {
    1 => println!("数字是 1"),
    2 | 3 | 5 | 7 | 11 => println!("这是一个质数"),
    13..=19 => println!("介于 13 到 19 之间"),
    _ => println!("其他数字"),
}

模式种类

  • 字面量匹配
  • 多模式匹配 (|)
  • 范围匹配 (..=)
  • 结构体、元组、枚举解构
  • 绑定变量

示例:枚举匹配

rust
enum Direction {
    Up,
    Down,
    Left,
    Right,
}

let dir = Direction::Left;

match dir {
    Direction::Up => println!("向上"),
    Direction::Down => println!("向下"),
    Direction::Left => println!("向左"),
    Direction::Right => println!("向右"),
}

代码演示

Rust Playground
打开运行
fn main() {
    let number = 7;
match number {
    1 => println!("数字是 1"),
    2 | 3 | 5 | 7 | 11 => println!("这是一个质数"),
    13..=19 => println!("介于 13 到 19 之间"),
    _ => println!("其他数字"),
}

enum Direction {
    Up,
    Down,
    Left,
    Right,
}

let dir = Direction::Left;

match dir {
    Direction::Up => println!("向上"),
    Direction::Down => println!("向下"),
    Direction::Left => println!("向左"),
    Direction::Right => println!("向右"),
}

}