Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

模式与匹配

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.

本章是关于模式相关所有内容的参考。我们将介绍使用模式的有效场所、可反驳(refutable)模式与不可反驳(irrefutable)模式的区别,以及你可能看到的各种模式语法。到本章结束时,你将学会如何使用模式以清晰的方式表达许多概念。

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.