# 模式匹配

模式匹配是一种编程语言构造，它将一个值与被描述的形状（称为模式）进行检验，当形状吻合时，将变量绑定到该值的各个部分。它推广了 switch 语句：不再仅仅将主体与常量进行比较，匹配可以解构元组、记录和代数数据类型，应用范围和字面量检验，并在一步中将匹配到的片段绑定到新变量。<sup>[1](https://doc.rust-lang.org/reference/patterns.html)</sup><sup> • </sup><sup>[2](https://drops.dagstuhl.de/entities/document/10.4230/LIPIcs.ECOOP.2025.2)</sup>

| 关键事实 | 详情 |
|---|---|
| 核心操作 | 模式将值与结构进行匹配，并可选地将变量绑定到这些结构内部的值；它们也出现在变量声明和函数参数中。<sup>[1](https://doc.rust-lang.org/reference/patterns.html)</sup> |
| 语义 | 大多数语言选择首次匹配语义：子句按出现顺序依次尝试，直到第一个匹配成功。<sup>[2](https://drops.dagstuhl.de/entities/document/10.4230/LIPIcs.ECOOP.2025.2)</sup> |
| 可反驳性 | 当一个模式可能无法匹配其所检验的值时，该模式是可反驳的；不可反驳的模式总是匹配成功。<sup>[1](https://doc.rust-lang.org/reference/patterns.html)</sup> |
| 编译 | 实现将模式翻译为自动机，最常见的是决策树，它从不对主体的给定子项测试超过一次。<sup>[3](https://www.cs.tufts.edu/~nr/pubs/match-abstract.html)</sup><sup> • </sup><sup>[4](https://citeseerx.ist.psu.edu/document?doi=aa003e97e38af183aa7bd1fbb2d615d5ae3f57f0&repid=rep1&type=pdf)</sup> |
| 编译器成本 | 唯一保证产生最小成本决策树的方法需要指数级的匹配编译时间，因此实际编译器使用启发式方法。<sup>[3](https://www.cs.tufts.edu/~nr/pubs/match-abstract.html)</sup> |
| 语言覆盖面 | 模式匹配是函数式、命令式和面向对象语言中广受欢迎的特性，C++ 正在推动 `match` 表达式进入 C++26。<sup>[2](https://drops.dagstuhl.de/entities/document/10.4230/LIPIcs.ECOOP.2025.2)</sup><sup> • </sup><sup>[5](https://open-std.org/JTC1/SC22/WG21/docs/papers/2026/p2688r6.html)</sup> |

## 模式做什么

一个模式将三项工作合于一个构造之中：检验、绑定和忽略。在 Rust 中，单个模式可以检验某个字段持有特定的变体，检验另一个字段落在诸如 13..=19 的范围之内同时将其值绑定到一个变量，绑定对第三个字段的引用，并用剩余模式忽略其余字段。<sup>[1](https://doc.rust-lang.org/reference/patterns.html)</sup> 解构将值拆分为其组成部分，而模式语法刻意模仿了用于构造该值的语法。<sup>[1](https://doc.rust-lang.org/reference/patterns.html)</sup>

**模式出现的位置。** 在 Rust 中，它们用于 `let` 声明、函数和闭包参数、`match` 表达式、`if let` 和 `while let` 表达式以及 `for` 循环。<sup>[1](https://doc.rust-lang.org/reference/patterns.html)</sup> 同样的广度也出现在其他地方：Python 将模式匹配添加为 `match` 语句，其 `case` 子句由模式及关联动作组成，并在 PEP 636 中为学习者提供了文档。<sup>[6](https://peps.python.org/pep-0636/)</sup>

**可反驳与不可反驳模式。** 可能失败的模式是可反驳的；总是匹配的模式是不可反驳的。在 Rust 中，`let (x, y) = (1, 2)` 使用不可反驳模式，而 `if let (a, 3) = (1, 2)` 使用可反驳模式，后者只是不匹配，因此 `else` 分支执行。<sup>[1](https://doc.rust-lang.org/reference/patterns.html)</sup> 这一区分决定了模式可以写在何处：必须总是成功的绑定只接受不可反驳模式，而条件上下文接受可反驳模式。

**首次匹配顺序。** 大多数语言赋予 match 首次匹配语义，按程序顺序尝试子句直到一个匹配成功。<sup>[2](https://drops.dagstuhl.de/entities/document/10.4230/LIPIcs.ECOOP.2025.2)</sup> 因此顺序具有意义：写在特定分支之前的兜底分支使特定分支不可达，这就是编译器还执行冗余检测的原因——验证每个分支都能被某个输入到达。<sup>[7](https://ori-lang.com/docs/compiler-design/07-canonicalization/pattern-compilation/)</sup>

## 匹配与合一

函数式语言中的模式匹配是单向的：模式是固定的，值被拿来与之检验。Haskell 的教程将其与 Prolog 等逻辑编程语言进行对比，后者通过合一允许双向匹配，并在求值机制中隐含回溯。<sup>[8](https://www.haskell.org/tutorial/patterns.html)</sup> 在 Haskell 中，模式也不是一等公民：只有固定的一组模式种类，不过允许与任何类型的构造器进行匹配，无论用户定义与否，包括元组、字符串、数字和字符。<sup>[8](https://www.haskell.org/tutorial/patterns.html)</sup> 如果函数定义中的所有等式都失败，则应用在运行时失败。<sup>[8](https://www.haskell.org/tutorial/patterns.html)</sup>

## 编译器如何实现

虽然模式匹配在形式上被规定为按顺序逐一将值与模式进行检验，但实际实现将模式编译为能够同时将值与众多模式进行匹配的自动机；其中决策树最为常用。<sup>[3](https://www.cs.tufts.edu/~nr/pubs/match-abstract.html)</sup> 两种编译模型占主导地位。编译为决策树是原始方法，首次出现在 Hope 编译器中。<sup>[9](https://hevea.inria.fr/~maranget/papers/opat/pat008.html)</sup> 另一种编译为回溯自动机，它可以沿不同路径重新测试同一子项，因此在运行时可能效率低下。<sup>[4](https://citeseerx.ist.psu.edu/document?doi=aa003e97e38af183aa7bd1fbb2d615d5ae3f57f0&repid=rep1&type=pdf)</sup>

**决策树。** 决策树的主要优点是从不对主体值的给定子项测试超过一次；主要缺点是可能导致代码体积爆炸。<sup>[4](https://citeseerx.ist.psu.edu/document?doi=aa003e97e38af183aa7bd1fbb2d615d5ae3f57f0&repid=rep1&type=pdf)</sup> 生成的树对子项的测试顺序敏感，因此编译器用启发式方法引导一个简单的归纳算法，并可能将树实现为具有最大共享的有向无环图以控制体积。<sup>[4](https://citeseerx.ist.psu.edu/document?doi=aa003e97e38af183aa7bd1fbb2d615d5ae3f57f0&repid=rep1&type=pdf)</sup>

**启发式方法有多重要。** 当时在[塔夫茨大学](https://www.edgepedia.org/zh/tufts-university)的 [Kevin Scott](https://www.edgepedia.org/zh/kevin-scott) 和 Norman Ramsey 在新泽西标准 ML 编译器中通过实验评估了匹配编译的启发式方法。他们的主要发现是，对于大多数基准程序，所有启发式方法产生的树大小相同，而对于少数程序，选择不同启发式方法对树大小的影响不超过几个百分点。机器生成的程序是例外：对于它们，正确或错误的启发式方法可以造成 2 到 20 倍的差异。<sup>[3](https://www.cs.tufts.edu/~nr/pubs/match-abstract.html)</sup> INRIA 的 Luc Maranget 后来受必要性启发设计了新的启发式方法——必要性是惰性模式匹配中的一个概念，他以决策树语义重新表述了它——并通过实验表明，由此产生的优化编译器与早期的 Le Fessant 和 Maranget（2001）匹配编译器具有竞争力。<sup>[10](https://researchr.org/publication/Maranget08)</sup>

**穷尽性与冗余性。** 编译器在编译前或编译期间检查两个静态属性：穷尽性，即每个可能的输入都能匹配至少一个分支；以及有用性，即每个分支都能被某个输入到达。在决策树编译中，两种分析自然得出：树中的 `Fail` 节点表示非穷尽性，而从未出现在任何叶子中的分支索引是冗余的。<sup>[7](https://ori-lang.com/docs/compiler-design/07-canonicalization/pattern-compilation/)</sup> 相比之下，朴素回溯对于 N 个分支和 M 列，每次匹配可能执行多达 N×M 次测试。<sup>[7](https://ori-lang.com/docs/compiler-design/07-canonicalization/pattern-compilation/)</sup>

## 超越代数数据类型

同样的思想也适用于结构化数据之外。SNOBOL 是 1960 年代的一种文本处理语言，具有异常强大的模式匹配以及字符串替换和置换功能，在 1970 年代和 1980 年代主导了专业文本分析领域。<sup>[11](https://asistdl.onlinelibrary.wiley.com/doi/10.1002/bult.2005.1720310607)</sup> 在字符串匹配中，Bruce W. Watson 和 Richard E. Watson 提出了一种针对以正则表达式给出的模式的 Boyer–Moore 型算法，回答了 [Alfred Aho](https://www.edgepedia.org/zh/alfred-aho) 在 1980 年提出的一个开放问题；与 Boyer–Moore 和 Commentz–Walter 一样，它使用预计算的移位函数，在测试中它经常优于 [Aho–Corasick 算法](https://www.edgepedia.org/zh/aho-corasick-algorithm)的正则表达式推广。<sup>[12](https://www.sciencedirect.com/science/article/pii/S0167642303000133)</sup> 研究人员还将结构模式匹配扩展到非结构化二进制数据——网络应用通常操作的格式。<sup>[13](https://www.cambridge.org/core/journals/journal-of-functional-programming/article/efficient-manipulation-of-binary-data-using-pattern-matching/5FC43829285903225B3BD0A52B1AD975)</sup>

## 近期的语言采纳

模式匹配一直在进入主流命令式和面向对象语言。一份 C++ 提案 P2688“使用 `match` 和 `case` 的模式匹配”达到了 EWG 投票通过将 `match` 表达式转发给 CWG 以纳入 C++26 的阶段；该提案指出，当今 C++ 分别通过 `switch`（用于整型和枚举值）、`if`（用于谓词）、结构化绑定（用于解构元组）、`std::visit`（用于 `std::variant` 备选）和 `dynamic_cast`（用于类层次结构）提供底层操作。<sup>[5](https://open-std.org/JTC1/SC22/WG21/docs/papers/2026/p2688r6.html)</sup> 一份较早的 C++ 论文主张将模式匹配建立在 `switch` 本身之上，指出 `switch` 已经是一种受限的模式匹配：它唯一的模式（连同通配符）是整数值常量表达式。<sup>[14](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/p2940r0.html)</sup> Python 的 `match` 语句随 PEP 634 引入并在 PEP 636 中教授，将同样的构造带入了动态类型语言。<sup>[6](https://peps.python.org/pep-0636/)</sup>

## References

1. [Patterns, The Rust Reference](https://doc.rust-lang.org/reference/patterns.html)
2. [The Algebra of Patterns, ECOOP 2025 (Dagstuhl)](https://drops.dagstuhl.de/entities/document/10.4230/LIPIcs.ECOOP.2025.2)
3. [Kevin Scott and Norman Ramsey, When Do Match-Compilation Heuristics Matter?](https://www.cs.tufts.edu/~nr/pubs/match-abstract.html)
4. [Luc Maranget, Compiling Pattern Matching to Good Decision Trees](https://citeseerx.ist.psu.edu/document?doi=aa003e97e38af183aa7bd1fbb2d615d5ae3f57f0&repid=rep1&type=pdf)
5. [Michael Park, Pattern Matching with `match` and `case` (P2688R6), C++ committee paper](https://open-std.org/JTC1/SC22/WG21/docs/papers/2026/p2688r6.html)
6. [PEP 636 – Structural Pattern Matching: Tutorial](https://peps.python.org/pep-0636/)
7. [Pattern Compilation, OriLang Compiler Design documentation](https://ori-lang.com/docs/compiler-design/07-canonicalization/pattern-compilation/)
8. [A Gentle Introduction to Haskell: Case Expressions and Pattern Matching](https://www.haskell.org/tutorial/patterns.html)
9. [Luc Maranget, Warnings for pattern matching, Related Work section](https://hevea.inria.fr/~maranget/papers/opat/pat008.html)
10. [Compiling pattern matching to good decision trees, ML'08, researchr entry](https://researchr.org/publication/Maranget08)
11. [Fosdick, Programming languages for library and textual processing, Bulletin of the American Society for Information Science and Technology](https://asistdl.onlinelibrary.wiley.com/doi/10.1002/bult.2005.1720310607)
12. [Bruce W. Watson and Richard E. Watson, A Boyer–Moore-style algorithm for regular expression pattern matching, Science of Computer Programming](https://www.sciencedirect.com/science/article/pii/S0167642303000133)
13. [Per Gustafsson and Konstantinos Sagonas, Efficient manipulation of binary data using pattern matching, Journal of Functional Programming](https://www.cambridge.org/core/journals/journal-of-functional-programming/article/efficient-manipulation-of-binary-data-using-pattern-matching/5FC43829285903225B3BD0A52B1AD975)
14. [switch for Pattern Matching (P2940R0), C++ committee paper](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/p2940r0.html)

---
*Initially written Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Programming languages › Programming language concepts

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/pattern-matching

English original: https://www.edgepedia.org/pattern-matching
