# 模式匹配 match

URL: https://caijiao.org/rust/07-advanced/01-pattern-matching
Source: docs/rust/07-advanced/01-pattern-matching.md
Description: Rust 的模式匹配通过 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 示例代码
