x-i18n: generated_at: “2026-03-01T14:53:45Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 6fcb23c2cc53ff1a4ea10ae3ba914a75678fa6b3cfc56645b22b1893b4fabb6d source_path: ch19-00-patterns.md workflow: 16
模式与匹配 (Patterns and Matching)
Patterns and Matching
模式是 Rust 中一种特殊的语法,用于匹配复杂或简单类型的结构。将模式与 match 表达式和其他结构结合使用,可以让你更好地控制程序的执行流。一个模式由以下内容的某种组合组成:
Patterns are a special syntax in Rust for matching against the structure of
types, both complex and simple. Using patterns in conjunction with match
expressions and other constructs gives you more control over a program’s
control flow. A pattern consists of some combination of the following:
- 字面量 (Literals)
- 解构的数组、枚举、结构体或元组 (Destructured arrays, enums, structs, or tuples)
- 变量 (Variables)
- 通配符 (Wildcards)
- 占位符 (Placeholders)
模式的一些例子包括 x 、 (a, 3) 和 Some(Color::Red) 。在模式有效的上下文中,这些组件描述了数据的形状。然后我们的程序将值与模式进行匹配,以确定它是否具有正确形状的数据来继续运行特定的代码片段。
Some example patterns include x, (a, 3), and Some(Color::Red). In the
contexts in which patterns are valid, these components describe the shape of
data. Our program then matches values against the patterns to determine whether
it has the correct shape of data to continue running a particular piece of code.
要使用模式,我们将其与某个值进行比较。如果模式与该值匹配,我们就在代码中使用该值的部分。回想一下第 6 章中使用了模式的 match 表达式,例如硬币分拣机的例子。如果值符合模式的形状,我们就可以使用命名的部分。如果不符合,与该模式关联的代码将不会运行。
To use a pattern, we compare it to some value. If the pattern matches the
value, we use the value parts in our code. Recall the match expressions in
Chapter 6 that used patterns, such as the coin-sorting machine example. If the
value fits the shape of the pattern, we can use the named pieces. If it
doesn’t, the code associated with the pattern won’t run.
本章是关于模式相关所有内容的参考。我们将涵盖使用模式的有效位置、可反驳模式与不可反驳模式之间的区别,以及你可能会看到的各种不同种类的模式语法。到本章结束时,你将知道如何使用模式以清晰的方式表达许多概念。
This chapter is a reference on all things related to patterns. We’ll cover the valid places to use patterns, the difference between refutable and irrefutable patterns, and the different kinds of pattern syntax that you might see. By the end of the chapter, you’ll know how to use patterns to express many concepts in a clear way.