Pattern Matching
Exhaustive pattern matching with match expressions, guards, and nested patterns.
模式匹配
match 表达式提供对值的穷举模式匹配。编译器会检查所有情况是否被覆盖,并对不可达的分支发出警告。
基本匹配
fn describe(x: i32) -> i64 {
match x {
0 => 0,
1 => 1,
_ => 2,
}
}
通配符 _ 匹配任意值,用作兜底分支。
匹配枚举
enum Shape {
Circle(f64),
Rectangle(f64, f64),
Triangle(f64, f64, f64),
}
fn sqrt(x: f64) -> f64 { x }
fn area(s: Shape) -> f64 {
match s {
Shape::Circle(r) => 3.14159 * r * r,
Shape::Rectangle(w, h) => w * h,
Shape::Triangle(a, b, c) => {
let s = (a + b + c) / 2.0
sqrt(s * (s - a) * (s - b) * (s - c))
},
}
}
如果遗漏了某个变体,编译器会报告非穷举匹配错误。
守卫条件
模式分支可以包含 if 守卫来添加额外条件:
fn classify_temp(celsius: f64) -> i64 {
match celsius {
t if t < 0.0 => 0,
t if t < 20.0 => 1,
t if t < 35.0 => 2,
_ => 3,
}
}
匹配结构体
struct Point { x: f64, y: f64 }
fn quadrant(p: Point) -> i64 {
match p {
Point { x, y } if x > 0.0 && y > 0.0 => 1,
Point { x, y } if x < 0.0 && y > 0.0 => 2,
Point { x, y } if x < 0.0 && y < 0.0 => 3,
Point { x, y } if x > 0.0 && y < 0.0 => 4,
_ => 0,
}
}
当前限制
let绑定中的元组解构(let (a, b) = pair)尚不支持,请改用match。- 深层嵌套结构体的嵌套模式匹配可以工作,但在所有情况下尚未完全实现穷举性检查。
- 或模式(
A | B => ...)已可解析,但其覆盖率检查仍在完善中。