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

枚举和模式匹配

Enums and Pattern Matching

在本章中,我们将讨论枚举(enumerations),也简称为“枚举”(enums)。枚举允许你通过枚举其可能存在的“变体”(variants)来定义一种类型。首先,我们将定义并使用一个枚举,展示枚举如何将意义与数据一起编码。接下来,我们将探索一个特别有用的枚举,名为 Option,它表达了一个值既可以是某个东西,也可以是无。然后,我们将了解 match 表达式中的模式匹配如何轻松地为枚举的不同值运行不同的代码。最后,我们将介绍 if let 结构是如何在代码中处理枚举的另一个方便且简洁的惯用法。

In this chapter, we’ll look at enumerations, also referred to as enums. Enums allow you to define a type by enumerating its possible variants. First we’ll define and use an enum to show how an enum can encode meaning along with data. Next, we’ll explore a particularly useful enum, called Option, which expresses that a value can be either something or nothing. Then, we’ll look at how pattern matching in the match expression makes it easy to run different code for different values of an enum. Finally, we’ll cover how the if let construct is another convenient and concise idiom available to handle enums in your code.