Pattern and Match

时间:2025-05-14 20:01:51

在 Rust 中,模式(pattern)是用来匹配某种结构化数据的语法结构。你可以把它理解为“结构匹配模板” —— Rust 根据这个模板去“解构”或“检查”一个值。

在这些语法中会使用“模式”:

  • let 声明
  • 函数和闭包的参数。
  • 匹配(match)表达式
  • if let 表达式
  • while let 表达式
  • for 表达式

Rust 的模式可以非常丰富,下面是 Rust 部分合法模式的分类和举例

通用模式分类

下面 PATTERN 代表模式

  • match

    match expr { PATTERN => ... }
    
  • let

    let PATTERN = ...
    
  • 附加 if 条件

    match expr { PATTERN if cond => ... }
    
  • for 循环

    for PATTERN in iter
    
  • if let

    if let PATTERN = expr
    
  • 函数参数

    fn func(PATTERN: Type)
    
  • while let

    while let PATTERN = expr
    

例子

通配符模式
match x {
	_ => println!("anything"),    // `_` 匹配任意值,但不会绑定。
}
字面量模式
// 匹配常量值、数字、字符、布尔、字符串等。
match x {
    1 => ...,
    'a' => ...,
    true => ...,
}
4. 路径模式(常量路径)
const A: i32 = 10;
enum Color { Red, Green, Blue }

// 匹配常量或枚举路径。
match x {
    A => ...,
    Color::Red => ...,
}
数组/切片模式
let arr = [1, 2, 3, 4];

// 匹配固定大小的数组(可部分使用 `..`)。
match arr {
    [a, b, ..] => ...,
    [1, .., 4] => ...,
}
模式组合
// 使用 `|` 连接多个模式(类似“或”逻辑)。
match x {
    1 | 2 | 3 => println!("1, 2, or 3"),
}
嵌套模式
// 模式中嵌入其他模式组合。
match something {
    Some((x, y)) => ...,
    _ => {},
}

if let Some((x, y)) = some_tuple_opt {
             ^^^^^ 模式 ← 解构嵌套元组
    println!("{x}, {y}");
}
范围模式(仅适用于整数和字符)
  • 匹配范围。
match x {
    1..=10 => println!("in range"),
    'a'..='z' => println!("lowercase letter"),
}
引用模式
// `&` 用于解构引用
let x = &5;
match x {
    &val => println!("{val}"),
}

// `ref` 用于绑定引用变量
let x = 5;
match x {
	ref r => println!("r is a reference to x: {}", r),
}

绑定模式(@ 绑定)

// 将匹配的值绑定到变量,同时验证模式
match 15 {
    x @ 1..=10 => "1-10",  // x = 15(不匹配)
    x @ 11..=20 => "11-20", // x = 15(匹配)
    _ => "other",
}
标识符绑定模式
let x = 5;
let y = x;           // `name` 绑定当前值到变量名。
let ref r = x;       // 引用绑定
let ref mut m = x;   // 可变引用绑定
结构体/枚举结构模式
// 匹配结构体
struct Point { x: i32, y: i32 }
let p = Point { x: 1, y: 2 };

// 匹配枚举结构。
enum Shape { Circle(i32), Rectangle { w: i32, h: i32 } }
let Shape::Rectangle { w, h } = shape;

let x = Some(5);
if let Some(v) = x {
         ^^^^^ 模式 ← 解构 Some 并绑定 v
    println!("v = {v}");
}
元组模式
// 匹配元组的每个元素
let (a, b) = (1, 2);
守卫模式(if guards)
match x {
    n if n > 10 => println!("greater than 10"),
    _ => {},
}
忽略剩余部分(Ignore Remaining ..
// 用 `..` 忽略未明确指定的部分:
struct S { a: i32, b: i32, c: i32 }
let s = S { a: 0, b: 1, c: 2 };
let S { a, .. } = s;  // 只绑定 `a`,忽略 `b` 和 `c`
类型转换模式(as Patterns)
// 将匹配的值转换为特定类型
let x: u8 = 1;
match x {
    n as u16 => println!("u16: {}", n),  // 转换类型
}
联合模式(Union Patterns)
// 用于匹配 `union` 类型的字段(需 `unsafe`):
union MyUnion { i: i32, f: f32 }
let u = MyUnion { i: 42 };
unsafe {
    match u {
        MyUnion { i: 42 } => "matched integer",
        _ => "other",
    }
}

官方文档参考

  • Rust Reference: Patterns
  • The Rust Book - Patterns