Rust 枚举类
核对 Rust 代数枚举(无载荷、元组变体、结构体变体)、match 穷尽模式匹配与表达式求值、Option<T> 替代空值设计及 if let 语法糖。
学完这一章,你能够
- 核对 Rust 代数枚举(无载荷、元组变体、结构体变体)、match 穷尽模式匹配与表达式求值、Option<T> 替代空值设计及 if let 语法糖。
枚举定义与三类变体载荷
Rust 的枚举(`enum`)本质上是带标签的联合体(Tagged Union)。最简形式如 `enum Book { Papery, Electronic }` 搭配 `#[derive(Debug)]` 可打印 `Papery`;进一步可以为各变体附加不同结构的数据——既可用元组载荷(如 `Papery(u32)`、`Electronic(String)`),也可用具名结构体载荷(如 `Papery { index: u32 }`、`Electronic { url: String }`)。需注意枚举变体内部字段不能像普通结构体那样直接点号访问,而需通过模式匹配解构提取。
match 穷尽模式匹配与返回值规则
Rust 不提供容易因遗漏 `break` 引发穿透 bug 的 `switch`,而是通过 `match` 实现模式匹配。`match` 既可解构具名变体(`Book::Papery { index } => ...`),也可为元组变体临时绑定变量名(`Book::Papery(i) => ...`);同时 `match` 是表达式,每个分支均可产生返回值,且编译器强制所有分支的返回类型一致、枚举所有变体必须被穷尽覆盖。
除枚举外,`match` 也可对整数、字符与 `&str` 等非枚举类型做分支选择(浮点数因精度及 `NaN` 语义在现代 Rust 中不推荐/逐步禁止直接用于模式匹配)。对开放值域类型匹配时,必须用通配符 `_` 兜底处理其余情况,即使分支体为空块 `{}`。本站离线校验器核对三类变体解构、遗漏变体被穷尽检查拒绝以及字符串 `"abc"` / `_` 匹配分支。
Option<T> 枚举与空值安全
为根除空指针引用造成的运行时崩溃,Rust 在语言层面取消了 `null`,改由标准库内置泛型枚举 `enum Option<T> { Some(T), None }` 显式表达“值可能缺失”。使用包裹值前必须通过 `match` 等手段显式区分 `Some(v)` 与 `None`,从而把空值检查前移到编译期。
当变量初始化为 `Option::None` 且上下文不足以推导 `T` 时,必须显式标注类型(如 `let opt: Option<&str> = Option::None;`)。因为 `Option`、`Some`、`None` 均已纳入默认 prelude,日常可直接写 `Some(64)` 与 `None`,并可在 `match` 中直接做嵌套字面量匹配(如 `Some(64) => ...`)。离线校验器验证了 `Some("Hello")`、显式类型 `None` 与 `Some(64)` 的分支结果。
if let 简洁匹配语法糖
当仅关心单一模式而忽略其他所有分支时,把 `match i { 0 => println!("zero"), _ => {} }` 改写为 `if let 0 = i { println!("zero"); }` 更紧凑;同样可在后方追加 `else` 块处理未命中分支,且完全适用于带载荷枚举解构(如 `if let Book::Papery(index) = book { ... } else { ... }`)。本质上 `if let` 是二分支 `match` 的语法糖,离线校验器已同步验证整数与 `Book::Electronic` 落入 `else` 分支的行为。
运行离线 Python 校验:Rust 枚举变体解构、match 穷尽检查、Option<T> 与 if let
展开查看收起
"""Offline Rust semantic verifier for Chapter 18: Enum (tagged unions, match exhaustiveness, Option, if let)."""
from dataclasses import dataclass
import json
from typing import Any, Callable
@dataclass(frozen=True)
class EnumVariant:
enum_name: str
tag: str
payload: Any = None
def match_exhaustive(
value: EnumVariant,
all_tags: set[str],
arms: dict[str, Callable[[Any], Any]],
wildcard: Callable[[], Any] | None = None,
) -> Any:
"""Enforces Rust match exhaustiveness and uniform arm return types."""
missing = all_tags - set(arms.keys())
if missing and wildcard is None:
raise TypeError(f"non-exhaustive patterns: missing {sorted(missing)}")
if value.tag in arms:
return arms[value.tag](value.payload)
assert wildcard is not None
return wildcard()
def run_cases() -> list[dict]:
cases = []
# Case 1: Unit, tuple, and struct-variant enums + match destructuring
book_tags = {"Papery", "Electronic"}
simple = EnumVariant("Book", "Papery")
tuple_book = EnumVariant("Book", "Papery", (1001,))
struct_book = EnumVariant("Book", "Papery", {"index": 1001})
struct_ebook = EnumVariant("Book", "Electronic", {"url": "https://example.org/rust"})
def describe_struct(b: EnumVariant) -> str:
return match_exhaustive(
b,
book_tags,
{
"Papery": lambda f: f"Papery book {f['index']}",
"Electronic": lambda f: f"E-book {f['url']}",
},
)
def describe_tuple(b: EnumVariant) -> str:
return match_exhaustive(
b,
book_tags,
{
"Papery": lambda t: str(t[0]),
"Electronic": lambda f: f["url"],
},
)
actual_1 = {
"simple_debug": simple.tag,
"struct_match_papery": describe_struct(struct_book),
"struct_match_ebook": describe_struct(struct_ebook),
"tuple_match": describe_tuple(tuple_book),
}
expected_1 = {
"simple_debug": "Papery",
"struct_match_papery": "Papery book 1001",
"struct_match_ebook": "E-book https://example.org/rust",
"tuple_match": "1001",
}
cases.append(dict(
name="enum_variants_and_match_destructuring",
summary="Verify unit, tuple, and struct enum variants destructured via exhaustive match",
expected=expected_1,
actual=actual_1,
passed=actual_1 == expected_1,
))
# Case 2: Exhaustiveness error + non-enum wildcard match
non_exhaustive_caught = False
try:
match_exhaustive(struct_book, book_tags, {"Papery": lambda f: f["index"]})
except TypeError:
non_exhaustive_caught = True
def match_str(val: str) -> str:
match val:
case "abc":
return "Yes"
case _:
return ""
actual_2 = {
"non_exhaustive_rejected": non_exhaustive_caught,
"str_match_abc": match_str("abc"),
"str_match_other": match_str("xyz"),
}
expected_2 = {
"non_exhaustive_rejected": True,
"str_match_abc": "Yes",
"str_match_other": "",
}
cases.append(dict(
name="match_exhaustiveness_and_wildcard",
summary="Verify missing enum arm is rejected and non-enum match uses _ catch-all arm",
expected=expected_2,
actual=actual_2,
passed=actual_2 == expected_2,
))
# Case 3: Option<T> Some/None and value-matching Some(64)
opt_tags = {"Some", "None"}
opt_hello = EnumVariant("Option", "Some", "Hello")
opt_none = EnumVariant("Option", "None", None)
opt_64 = EnumVariant("Option", "Some", 64)
def handle_opt(opt: EnumVariant) -> str:
return match_exhaustive(
opt,
opt_tags,
{
"Some": lambda v: str(v),
"None": lambda _: "opt is nothing",
},
)
val_match = "Yes" if (opt_64.tag == "Some" and opt_64.payload == 64) else "No"
actual_3 = {
"some_hello": handle_opt(opt_hello),
"typed_none": handle_opt(opt_none),
"some_64_match": val_match,
}
expected_3 = {
"some_hello": "Hello",
"typed_none": "opt is nothing",
"some_64_match": "Yes",
}
cases.append(dict(
name="option_some_none_matching",
summary="Verify Option<T> replaces null via Some/None and supports nested literal matching",
expected=expected_3,
actual=actual_3,
passed=actual_3 == expected_3,
))
# Case 4: if let syntax sugar with else branch
i = 0
zero_msg = "zero" if i == 0 else "other"
ebook_val = EnumVariant("Book", "Electronic", ("url",))
if ebook_val.tag == "Papery":
if_let_msg = f"Papery {ebook_val.payload[0]}"
else:
if_let_msg = "Not papery book"
actual_4 = {
"if_let_int": zero_msg,
"if_let_enum_else": if_let_msg,
}
expected_4 = {
"if_let_int": "zero",
"if_let_enum_else": "Not papery book",
}
cases.append(dict(
name="if_let_sugar_and_else",
summary="Verify if let shortens two-branch match for both literals and enum variants",
expected=expected_4,
actual=actual_4,
passed=actual_4 == expected_4,
))
return cases
def main() -> None:
payload = {
"version": "CPython 3.12.14 offline Rust semantic verifier (rustc absent)",
"cases": run_cases(),
}
print(json.dumps(payload, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
None 本身不携带内部值,编译器无法凭空推断泛型参数 T 的具体类型,必须通过显式类型标注或后续上下文确定;当需要穷尽检查所有变体以防新增枚举项被遗漏时应使用 match,仅关心单分支时可用 if let。