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


x-i18n: generated_at: “2026-03-01T13:46:29Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: efa473933293ae1d6cdca81c2efd61e9d2a602d43f4b8978b7bd145ec8e6c2c1 source_path: ch06-00-enums.md workflow: 16

枚举与模式匹配 (Enums and Pattern Matching)

Enums and Pattern Matching

在本章中,我们将研究枚举 (enumerations),也称为“enums”。枚举允许你通过列举其可能的变体来定义一种类型。首先,我们将定义并使用一个枚举,以展示枚举如何将含义与数据一起编码。接下来,我们将探索一个特别有用的枚举,名为 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.