泛型枚举
核心概念
泛型枚举是在枚举名后用尖括号声明类型参数的枚举,让不同变体可以携带参数化的数据类型。Rust 标准库中最重要的两个类型——Option<T> 和 Result<T, E>——就是泛型枚举。泛型枚举的核心价值在于:用一个枚举定义就能表达不同类型数据的"或"关系,同时保持完整的类型安全。
// 标准库中最常见的两个泛型枚举
// Option<T>:值可能有,也可能没有
// enum Option<T> {
// Some(T),
// None,
// }
// Result<T, E>:操作可能成功(Ok),也可能失败(Err)
// enum Result<T, E> {
// Ok(T),
// Err(E),
// }
fn divide(a: f64, b: f64) -> Option<f64> {
if b == 0.0 {
None
} else {
Some(a / b)
}
}
fn parse_number(s: &str) -> Result<i32, String> {
s.parse::<i32>().map_err(|e| format!("解析 '{}' 失败: {}", s, e))
}
fn main() {
// Option<f64>
println!("10 / 3 = {:?}", divide(10.0, 3.0));
println!("10 / 0 = {:?}", divide(10.0, 0.0));
// Result<i32, String>
println!("'42' = {:?}", parse_number("42"));
println!("'abc' = {:?}", parse_number("abc"));
}自定义泛型枚举
// 单个类型参数的泛型枚举
#[derive(Debug)]
enum Container<T> {
Empty,
Single(T),
Multiple(Vec<T>),
}
impl<T> Container<T> {
fn new() -> Self {
Container::Empty
}
fn from_value(value: T) -> Self {
Container::Single(value)
}
fn from_vec(values: Vec<T>) -> Self {
if values.is_empty() {
Container::Empty
} else if values.len() == 1 {
// 从 Vec 中取出唯一的元素
let mut v = values;
Container::Single(v.remove(0))
} else {
Container::Multiple(values)
}
}
fn is_empty(&self) -> bool {
matches!(self, Container::Empty)
}
fn count(&self) -> usize {
match self {
Container::Empty => 0,
Container::Single(_) => 1,
Container::Multiple(v) => v.len(),
}
}
}
impl<T: std::fmt::Display> Container<T> {
fn describe(&self) {
match self {
Container::Empty => println!("空容器"),
Container::Single(v) => println!("单值: {}", v),
Container::Multiple(v) => {
let items: Vec<String> = v.iter().map(|x| x.to_string()).collect();
println!("多值: [{}]", items.join(", "));
}
}
}
}
fn main() {
let c1: Container<i32> = Container::new();
let c2 = Container::from_value(42);
let c3 = Container::from_vec(vec![1, 2, 3, 4, 5]);
c1.describe();
c2.describe();
c3.describe();
println!("数量: {}, {}, {}", c1.count(), c2.count(), c3.count());
}多个类型参数的泛型枚举
use std::fmt;
// 两个类型参数:类似 Result 的设计
#[derive(Debug)]
enum Response<T, E> {
Success(T),
Error(E),
Pending,
}
impl<T, E> Response<T, E> {
fn is_success(&self) -> bool {
matches!(self, Response::Success(_))
}
fn is_error(&self) -> bool {
matches!(self, Response::Error(_))
}
fn is_pending(&self) -> bool {
matches!(self, Response::Pending)
}
// 将成功值取出,或用默认值替代
fn unwrap_or(self, default: T) -> T {
match self {
Response::Success(v) => v,
_ => default,
}
}
// 转换成功值的类型
fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Response<U, E> {
match self {
Response::Success(v) => Response::Success(f(v)),
Response::Error(e) => Response::Error(e),
Response::Pending => Response::Pending,
}
}
// 转换错误值的类型
fn map_err<F2, G: FnOnce(E) -> F2>(self, f: G) -> Response<T, F2> {
match self {
Response::Success(v) => Response::Success(v),
Response::Error(e) => Response::Error(f(e)),
Response::Pending => Response::Pending,
}
}
}
impl<T: fmt::Display, E: fmt::Display> fmt::Display for Response<T, E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Response::Success(v) => write!(f, "成功: {}", v),
Response::Error(e) => write!(f, "错误: {}", e),
Response::Pending => write!(f, "等待中"),
}
}
}
fn fetch_data(id: u32) -> Response<String, String> {
match id {
1 => Response::Success(String::from("用户数据")),
2 => Response::Error(String::from("用户不存在")),
_ => Response::Pending,
}
}
fn main() {
for id in 1..=3 {
let resp = fetch_data(id);
println!("请求#{}: {}", id, resp);
}
// map 转换
let resp = fetch_data(1);
let upper = resp.map(|s| s.to_uppercase());
println!("转换后: {}", upper);
// unwrap_or
let resp = fetch_data(2);
let value = resp.unwrap_or(String::from("默认值"));
println!("取值: {}", value);
}变体携带不同泛型类型的数据
// 不同变体使用不同的类型参数
#[derive(Debug)]
enum Either<L, R> {
Left(L),
Right(R),
}
impl<L, R> Either<L, R> {
fn is_left(&self) -> bool {
matches!(self, Either::Left(_))
}
fn is_right(&self) -> bool {
matches!(self, Either::Right(_))
}
fn left(self) -> Option<L> {
match self {
Either::Left(v) => Some(v),
Either::Right(_) => None,
}
}
fn right(self) -> Option<R> {
match self {
Either::Left(_) => None,
Either::Right(v) => Some(v),
}
}
// 对 Left 值做变换
fn map_left<U, F: FnOnce(L) -> U>(self, f: F) -> Either<U, R> {
match self {
Either::Left(v) => Either::Left(f(v)),
Either::Right(v) => Either::Right(v),
}
}
// 对 Right 值做变换
fn map_right<U, F: FnOnce(R) -> U>(self, f: F) -> Either<L, U> {
match self {
Either::Left(v) => Either::Left(v),
Either::Right(v) => Either::Right(f(v)),
}
}
}
fn classify_input(input: &str) -> Either<i32, String> {
match input.parse::<i32>() {
Ok(n) => Either::Left(n), // 是数字
Err(_) => Either::Right(input.to_string()), // 是文本
}
}
fn main() {
let inputs = vec!["42", "hello", "100", "world"];
for input in &inputs {
let result = classify_input(input);
match &result {
Either::Left(n) => println!("'{}' → 数字 {}", input, n),
Either::Right(s) => println!("'{}' → 文本 '{}'", input, s),
}
}
// map 变换
let val = classify_input("42");
let doubled = val.map_left(|n| n * 2);
println!("\n翻倍: {:?}", doubled);
}递归泛型枚举
泛型枚举可以递归定义,用 Box 避免无限大小。
// 泛型链表
#[derive(Debug)]
enum List<T> {
Cons(T, Box<List<T>>), // 节点:值 + 下一个节点
Nil, // 结束标记
}
impl<T> List<T> {
fn new() -> Self {
List::Nil
}
// 在头部添加元素
fn prepend(self, value: T) -> Self {
List::Cons(value, Box::new(self))
}
fn len(&self) -> usize {
match self {
List::Nil => 0,
List::Cons(_, next) => 1 + next.len(),
}
}
fn is_empty(&self) -> bool {
matches!(self, List::Nil)
}
}
impl<T: std::fmt::Display> List<T> {
fn print(&self) {
let mut current = self;
print!("[");
let mut first = true;
loop {
match current {
List::Nil => break,
List::Cons(value, next) => {
if !first { print!(" → "); }
print!("{}", value);
first = false;
current = next;
}
}
}
println!("]");
}
}
// 泛型二叉树
#[derive(Debug)]
enum Tree<T> {
Leaf(T),
Node {
value: T,
left: Box<Tree<T>>,
right: Box<Tree<T>>,
},
}
impl<T: std::fmt::Display> Tree<T> {
fn depth(&self) -> usize {
match self {
Tree::Leaf(_) => 1,
Tree::Node { left, right, .. } => {
1 + left.depth().max(right.depth())
}
}
}
fn count(&self) -> usize {
match self {
Tree::Leaf(_) => 1,
Tree::Node { left, right, .. } => {
1 + left.count() + right.count()
}
}
}
}
fn main() {
// 链表
let list = List::new()
.prepend(3)
.prepend(2)
.prepend(1);
list.print();
println!("长度: {}", list.len());
// 字符串链表
let str_list = List::new()
.prepend("world")
.prepend("hello");
str_list.print();
// 二叉树
let tree = Tree::Node {
value: 1,
left: Box::new(Tree::Node {
value: 2,
left: Box::new(Tree::Leaf(4)),
right: Box::new(Tree::Leaf(5)),
}),
right: Box::new(Tree::Leaf(3)),
};
println!("\n树深度: {}", tree.depth());
println!("节点数: {}", tree.count());
}基本示例
用泛型枚举实现一个任务状态机和加载状态管理:
use std::fmt;
// 异步加载状态
#[derive(Debug)]
enum LoadState<T, E> {
NotStarted,
Loading,
Loaded(T),
Failed(E),
Refreshing(T), // 有旧数据,正在刷新
}
impl<T, E> LoadState<T, E> {
fn is_loading(&self) -> bool {
matches!(self, LoadState::Loading | LoadState::Refreshing(_))
}
fn has_data(&self) -> bool {
matches!(self, LoadState::Loaded(_) | LoadState::Refreshing(_))
}
// 获取数据(如果有的话)
fn data(&self) -> Option<&T> {
match self {
LoadState::Loaded(d) | LoadState::Refreshing(d) => Some(d),
_ => None,
}
}
// 状态转换:开始加载
fn start_loading(self) -> Self {
match self {
LoadState::Loaded(data) => LoadState::Refreshing(data),
_ => LoadState::Loading,
}
}
// 状态转换:加载成功
fn finish_ok(self, data: T) -> Self {
LoadState::Loaded(data)
}
// 状态转换:加载失败
fn finish_err(self, error: E) -> Self {
LoadState::Failed(error)
}
}
impl<T: fmt::Display, E: fmt::Display> fmt::Display for LoadState<T, E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
LoadState::NotStarted => write!(f, "未开始"),
LoadState::Loading => write!(f, "加载中..."),
LoadState::Loaded(data) => write!(f, "已加载: {}", data),
LoadState::Failed(err) => write!(f, "失败: {}", err),
LoadState::Refreshing(data) => write!(f, "刷新中(当前: {})", data),
}
}
}
// 表达式求值器
#[derive(Debug)]
enum Expr<T> {
Value(T),
Add(Box<Expr<T>>, Box<Expr<T>>),
Mul(Box<Expr<T>>, Box<Expr<T>>),
Neg(Box<Expr<T>>),
}
impl Expr<f64> {
fn eval(&self) -> f64 {
match self {
Expr::Value(v) => *v,
Expr::Add(a, b) => a.eval() + b.eval(),
Expr::Mul(a, b) => a.eval() * b.eval(),
Expr::Neg(a) => -a.eval(),
}
}
}
impl<T: fmt::Display> fmt::Display for Expr<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Expr::Value(v) => write!(f, "{}", v),
Expr::Add(a, b) => write!(f, "({} + {})", a, b),
Expr::Mul(a, b) => write!(f, "({} * {})", a, b),
Expr::Neg(a) => write!(f, "(-{})", a),
}
}
}
fn main() {
// === 加载状态 ===
println!("=== 加载状态 ===");
let mut state: LoadState<String, String> = LoadState::NotStarted;
println!("1. {}", state);
state = state.start_loading();
println!("2. {}", state);
state = state.finish_ok(String::from("用户列表"));
println!("3. {}", state);
println!(" 有数据: {}", state.has_data());
state = state.start_loading();
println!("4. {}", state); // 刷新中,保留旧数据
println!(" 当前数据: {:?}", state.data());
state = state.finish_ok(String::from("更新后的用户列表"));
println!("5. {}", state);
// 模拟失败
let mut state2: LoadState<Vec<i32>, String> = LoadState::NotStarted;
state2 = state2.start_loading();
state2 = state2.finish_err(String::from("网络超时"));
println!("6. {}", state2);
// === 表达式求值 ===
println!("\n=== 表达式求值 ===");
// (2 + 3) * (-(4))
let expr = Expr::Mul(
Box::new(Expr::Add(
Box::new(Expr::Value(2.0)),
Box::new(Expr::Value(3.0)),
)),
Box::new(Expr::Neg(
Box::new(Expr::Value(4.0)),
)),
);
println!("表达式: {}", expr);
println!("结果: {}", expr.eval());
// 3 + (2 * 5)
let expr2 = Expr::Add(
Box::new(Expr::Value(3.0)),
Box::new(Expr::Mul(
Box::new(Expr::Value(2.0)),
Box::new(Expr::Value(5.0)),
)),
);
println!("表达式: {}", expr2);
println!("结果: {}", expr2.eval());
}常见问题
问题一:Option 和 Result 算泛型枚举吗?
是的,它们是标准库中最重要的泛型枚举。Option<T> 有一个类型参数,Result<T, E> 有两个类型参数。它们被预导入(prelude)到每个 Rust 程序中,不需要 use 就能直接使用。
问题二:泛型枚举的内存大小怎么算?
和普通枚举一样,泛型枚举的大小等于最大变体的大小加上判别值。但由于 Rust 的空位优化(niche optimization),Option<Box<T>> 和 Box<T> 大小相同(None 用空指针表示)。
问题三:为什么递归枚举需要 Box?
因为编译器需要在编译时确定类型的大小。递归枚举如果不用 Box,大小就变成无限了(List 包含 List 包含 List……)。Box<T> 是一个固定大小的指针,打破了无限递归。
问题四:泛型枚举可以有多少个类型参数?
理论上没有限制,但实际中很少超过 3 个。参数太多会让代码难以阅读和使用。
适用场景
- 可选值:
Option<T>表示有或无 - 错误处理:
Result<T, E>表示成功或失败 - 状态机:不同状态携带不同数据
- 递归数据结构:链表、树等
- 表达式树:编译器、解释器中的 AST
注意事项
- 泛型枚举的类型参数在
impl块中需要重新声明 - 可以为特定类型参数实现专属方法(如
impl Expr<f64>) - 递归泛型枚举必须通过
Box间接引用 matches!宏可以简洁地检查变体- 泛型枚举和泛型结构体一样会被单态化
- 不同类型参数的枚举实例是不同类型
总结
泛型枚举通过类型参数让枚举变体携带参数化的数据类型,是 Rust 类型系统中极其重要的组成部分。标准库的 Option<T> 和 Result<T, E> 是最典型的泛型枚举。自定义泛型枚举可以表达状态机(不同状态携带不同数据)、二选一(Either<L, R>)、递归数据结构(链表、树)等场景。泛型枚举支持多个类型参数,可以为所有类型或特定类型实现方法,递归定义时需要 Box 打破无限大小。泛型枚举配合模式匹配使用,编译器会强制检查所有变体是否被处理。