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

ch06 枚举和模式匹配

对应原书:ch06 枚举和模式匹配(ch06-01 定义枚举 / ch06-02 match 控制流 / ch06-03 if let)

上一节的 struct 适合“字段同时存在“的数据。这一节讲另一种打包方式: 一次只能是其中一种的情况。

enum:一次只能是其中一种

Rust 的 enum 每个变体可以携带不同的数据,不只是给整数起名字。

先看简单的:

#[derive(Debug)]
enum Direction {
    North,
    South,
    East,
    West,
}

fn main() {
    let d = Direction::North;
    println!("{d:?}");
}

再看真正有用的 —— 变体带数据,而且每个变体带的东西可以不一样:

#[derive(Debug)]
enum Shape {
    Circle { radius: f64 },                    // 带命名字段(像结构体)
    Rectangle { width: f64, height: f64 },
    Triangle(f64, f64),                        // 带位置字段(像元组)
    Unit,                                      // 什么都不带
}

fn main() {
    let shapes = [
        Shape::Circle { radius: 1.0 },
        Shape::Rectangle { width: 3.0, height: 4.0 },
        Shape::Triangle(6.0, 2.0),
        Shape::Unit,
    ];

    for s in &shapes {
        println!("{s:?}");
    }
}

关键认知:Shape::Circle 和 Shape::Rectangle 是同一个类型的不同取值, 但它们携带的数据完全不同。这在 C 里要用 tagged union 手动实现,而且容易出错。

Option<T>:Rust 没有 null

这是 enum 最重要的应用,你必须马上掌握。

Rust 通常用 Option<T> 表示“可能有一个值,也可能没有值”。 它是标准库定义的枚举,T 是内部值的类型:Option<i32> 的 T 就是 i32。 它有两个变体:Some(T) 携带一个值,None 不携带值。Some、None 默认已在作用域中,不需要另写 use。

fn main() {
    // Option<T> 在标准库里就是这么定义的:
    // enum Option<T> { Some(T), None }

    let found: Option<i32> = Some(42);
    let missing: Option<i32> = None;

    println!("{found:?} {missing:?}");
}

Option<T> 和 T 是不同的类型,不能直接当数字用:

fn main() {
    let x: Option<i32> = Some(5);
    let y = x + 1; // 编译不过
    println!("{y}");
}
error[E0369]: cannot add `{integer}` to `Option<{integer}>`

这就是它相对 null 的核心优势:Option<i32> 不实现 +, 所以不能直接把它当作整数相加,必须先决定怎样取值或处理没有值的情况。 这不保证程序一定不会 panic:取值操作仍需要正确处理 None;第 9 章会讲解可能触发 panic 的取值方法。

match:处理 enum 的标准工具

match 值 { 模式 => 处理方式, ... } 根据值选择分支。它也能匹配整数、元组和结构体, 并不限于枚举;后面的骰子例子会匹配整数。

#[derive(Debug)]
enum Shape {
    Circle { radius: f64 },
    Rectangle { width: f64, height: f64 },
    Unit,
}

fn area(s: &Shape) -> f64 {
    match s {
        // 把字段"拆"出来用
        Shape::Circle { radius } => 3.14159 * radius * radius,
        Shape::Rectangle { width, height } => width * height,
        Shape::Unit => 0.0,
    }
}

fn main() {
    println!("{}", area(&Shape::Circle { radius: 2.0 }));
    println!("{}", area(&Shape::Rectangle { width: 3.0, height: 4.0 }));
    println!("{}", area(&Shape::Unit));
}

在 match s 中,被检查的是参数 s 所引用的实际值。 Shape::Circle { radius } 是一个模式,规定这个分支只接收 Circle 变体。 例如传入 Rectangle 时,它不匹配这个模式,会继续尝试下一分支。

匹配成功后,字段 radius 的内容被绑定到同名的新变量上,供 => 后的代码使用。 因为这里 s 是 &Shape,Rust 自动按借用来匹配,变量 radius 是 &f64,没有搬走字段。

也可以写 Shape::Circle { radius: r }:左侧 radius 必须是定义中的字段名, 右侧 r 是你起的变量名,此时分支表达式相应写成 3.14159 * r * r。 Shape::Circle { radius } 就是 Shape::Circle { radius: radius } 的简写。 构造值时的 Shape::Circle { radius: 2.0 } 提供字段值;分支中的模式则检查并拆出已有值。

字段多了不想全拆时,用 ..:

#[derive(Debug)]
enum Shape {
    Circle { radius: f64 },
    Unit,
}

fn describe(s: &Shape) -> String {
    match s {
        Shape::Circle { .. } => String::from("圆的"), // .. 表示"字段我不管"
        Shape::Unit => String::from("啥也不是"),
    }
}

fn main() {
    println!("{}", describe(&Shape::Unit));
}

match 必须覆盖所有情况

少写一个变体,编译器拒绝:

#[derive(Debug)]
enum Shape {
    Circle { radius: f64 },
    Unit,
}

fn describe(s: &Shape) -> String {
    match s {
        Shape::Circle { .. } => String::from("圆的"),
        // 少了 Shape::Unit
    }
}

fn main() {}
error[E0004]: non-exhaustive patterns: `Shape::Unit` not covered

这是 Rust 特别有价值的一点:以后给 enum 加一个变体,没有兜底分支且没处理新变体的 match 会编译失败, 编译器会挨个告诉你哪里要改。几万行的项目里重构时这是救命的。

通配模式和 _ 占位符

有时只需要单独处理几个值,其余值执行同一种操作。比如掷骰子: 掷出 3 得到帽子,掷出 7 失去帽子,其余数字表示移动的格数。

fn action(dice_roll: u8) -> String {
    match dice_roll {
        3 => String::from("得到帽子"),
        7 => String::from("失去帽子"),
        other => format!("移动 {other} 格"), // 绑定其余值,供分支使用
    }
}

fn main() {
    println!("{:?}", action(3)); // 预期:"得到帽子"
    assert_eq!(action(3), "得到帽子");
    println!("{:?}", action(7)); // 预期:"失去帽子"
    assert_eq!(action(7), "失去帽子");
    println!("{:?}", action(9)); // 预期:"移动 9 格"
    assert_eq!(action(9), "移动 9 格");
}

other 是我们起的变量名,它匹配所有剩余值,并把值绑定到变量上。 因此不用把 u8 的所有数值逐个列出来,也能满足穷尽性要求。

如果规则变成“其他数字都重新掷”,不需要知道具体数字,就用 _ 占位符:

fn action(dice_roll: u8) -> String {
    match dice_roll {
        3 => String::from("得到帽子"),
        7 => String::from("失去帽子"),
        _ => String::from("重新掷骰子"), // 匹配任意剩余值,不绑定变量
    }
}

fn main() {
    println!("{:?}", action(3)); // 预期:"得到帽子"
    assert_eq!(action(3), "得到帽子");
    println!("{:?}", action(7)); // 预期:"失去帽子"
    assert_eq!(action(7), "失去帽子");
    println!("{:?}", action(9)); // 预期:"重新掷骰子"
    assert_eq!(action(9), "重新掷骰子");
    println!("{:?}", action(1)); // 预期:"重新掷骰子"
    assert_eq!(action(1), "重新掷骰子");
}

_ 匹配任意值,但不把值绑定到变量上。 => 把模式和要执行的代码分开, 所以 _ => ... 的意思就是“其余情况执行这段代码”。 other 和 _ 这种兜底分支应放在最后;match 按顺序匹配,命中一个分支就停止, 放在兜底分支后面的模式会不可达,编译器会警告。

如果其他数字什么都不做,可以写 _ => ():

fn main() {
    let dice_roll = 9;

    match dice_roll {
        3 => println!("得到帽子"),
        7 => println!("失去帽子"),
        _ => (), // 返回单元值,什么也不做
    }
}

这里的 () 是单元值(空元组),与前两个 println! 分支的返回类型一致。 因为 9 命中最后一个分支,这个程序不会打印内容。

对枚举使用兜底分支时,要想清楚新增变体是否也应执行默认操作。 _ => 仍然满足穷尽性检查;但以后增加的枚举变体也会被它匹配, 编译器就不会提醒你为新变体单独写分支。变量形式的 other => 也有同样的效果。 如果每个变体都需要明确处理,建议逐个列出,以便增加变体时得到编译器提醒。

enum 的真正威力:让非法状态无法表示

枚举也能定义方法

和结构体一样,枚举也可以写 impl,把行为放在类型上:

enum Signal {
    Stop,
    Go,
}

impl Signal {
    fn can_move(&self) -> bool {
        match self {
            Signal::Stop => false,
            Signal::Go => true,
        }
    }
}

fn main() {
    println!("{}", !Signal::Stop.can_move()); // 预期:true
    assert!(!Signal::Stop.can_move());
    println!("{}", Signal::Go.can_move()); // 预期:true
    assert!(Signal::Go.can_move());
}

调用方法不需要先从枚举里取出数据;方法内部可以用 match 处理不同变体。

用状态建模

这是本节的核心思想,值得单独理解。

假设你在写网络连接,有三种状态。用三个 bool 写:

#[derive(Debug)]
struct Connection {
    is_connecting: bool,
    is_connected: bool,
    is_disconnected: bool,
}

fn main() {
    // 这段代码能编译!但它描述的状态是荒谬的
    let c = Connection {
        is_connecting: true,
        is_connected: true,
        is_disconnected: true,
    };
    println!("{c:?}");
}

每个 bool 都有 true、false 两种取值,三个字段独立组合就是 2 × 2 × 2 = 8 种。 这里的业务规则是恰好一个状态为 true,所以只有 (true, false, false)、 (false, true, false)、(false, false, true) 三种合法。全 false 或多个 true 都不合法。 普通的三个 bool 字段没有表达这个规则;编译器只检查字段是不是 bool,不能据此拒绝这些组合。

用 enum:

#[derive(Debug)]
enum Connection {
    Connecting,
    Connected,
    Disconnected { reason: String },
}

fn describe(c: &Connection) -> String {
    match c {
        Connection::Connecting => String::from("连接中…"),
        Connection::Connected => String::from("已连接"),
        Connection::Disconnected { reason } => format!("已断开:{reason}"),
    }
}

fn main() {
    let states = [
        Connection::Connecting,
        Connection::Connected,
        Connection::Disconnected { reason: "用户关闭".to_string() },
    ];

    for s in &states {
        println!("{}", describe(s));
    }
}

现在“同时连接中又已连接“在类型层面就不可能表示。你不需要写检查代码, 因为非法状态根本构造不出来。

设计判据:写下你要的字段,然后问“它们能不能同时成立?“ 同时需要保存的属性通常用 struct;互斥的几种情况通常用 enum。 两者可以组合:结构体里可以有枚举字段,枚举变体也可以携带结构体。

if let:只处理匹配成功的情况

if let 用来检查一个值是否符合某个模式,匹配成功时才执行代码块。 它不只适用于 Option,也适用于自己定义的枚举。Option 本身就是一个枚举, Some 和 None 是它的两个变体。

基本写法是:if let 模式 = 要检查的值 { 匹配成功时执行的代码 }。 例如 if let Some(n) = value 检查 value 是否是 Some,并把里面的值绑定给 n; if let TrafficLight::Red = light 则检查 light 是否是 Red。

下面先用 Option 举例,再用自己定义的信号灯枚举对照 if let 与 match。

if let 还可以带 else,处理所有没匹配上的情况:

fn describe(value: Option<i32>) -> String {
    if let Some(n) = value {
        format!("读到 {n}")
    } else {
        String::from("没有值")
    }
}

fn main() {
    println!("{:?}", describe(Some(5))); // 预期:"读到 5"
    assert_eq!(describe(Some(5)), "读到 5");
    println!("{:?}", describe(None)); // 预期:"没有值"
    assert_eq!(describe(None), "没有值");
}

这个 else 处理所有不符合 Some(n) 的值,相当于下面 match 中的 _ 兜底分支:

fn describe(value: Option<i32>) -> String {
    match value {
        Some(n) => format!("读到 {n}"),
        _ => String::from("没有值"), // Option 只有 Some 和 None,这里剩下的就是 None
    }
}

fn main() {
    println!("{:?}", describe(Some(5))); // 预期:"读到 5"
    assert_eq!(describe(Some(5)), "读到 5");
    println!("{:?}", describe(None)); // 预期:"没有值"
    assert_eq!(describe(None), "没有值");
}

这里的 _ 也可以直接写成 None,明确指出没有值的情况。

如果枚举有多个变体,而且每个变体都要分别处理,用 match 把它们逐个列出更清楚。 例如,三种信号灯分别给出不同的提示:

enum TrafficLight {
    Red,
    Yellow,
    Green,
}

fn instruction(light: TrafficLight) -> String {
    match light {
        TrafficLight::Red => String::from("停车"),
        TrafficLight::Yellow => String::from("等待"),
        TrafficLight::Green => String::from("通行"),
    }
}

fn main() {
    println!("{:?}", instruction(TrafficLight::Red)); // 预期:"停车"
    assert_eq!(instruction(TrafficLight::Red), "停车");
    println!("{:?}", instruction(TrafficLight::Yellow)); // 预期:"等待"
    assert_eq!(instruction(TrafficLight::Yellow), "等待");
    println!("{:?}", instruction(TrafficLight::Green)); // 预期:"通行"
    assert_eq!(instruction(TrafficLight::Green), "通行");
}

同一个枚举也可以用 if let。下面只区分“红灯”和“不是红灯”:

enum TrafficLight {
    Red,
    Yellow,
    Green,
}

fn instruction(light: TrafficLight) -> String {
    if let TrafficLight::Red = light {
        String::from("停车")
    } else {
        String::from("不是红灯,还需要区分黄灯和绿灯")
    }
}

fn main() {
    println!("{:?}", instruction(TrafficLight::Red)); // 预期:"停车"
    assert_eq!(instruction(TrafficLight::Red), "停车");
    // Yellow 和 Green 都不匹配 Red,所以都会进入 else。
    println!("{:?}", instruction(TrafficLight::Yellow)); // 预期:"不是红灯,还需要区分黄灯和绿灯"
    assert_eq!(instruction(TrafficLight::Yellow), "不是红灯,还需要区分黄灯和绿灯");
    println!("{:?}", instruction(TrafficLight::Green)); // 预期:"不是红灯,还需要区分黄灯和绿灯"
    assert_eq!(instruction(TrafficLight::Green), "不是红灯,还需要区分黄灯和绿灯");
}

if let 这里只检查是否为 Red,else 会同时接住 Yellow 和 Green, 还需要进一步判断才能分别处理。前面的 match 直接列出了三种情况及各自的处理方式。

let else:把“否则就退出“写在一行

不带 else 的 if let 在匹配失败时会跳过代码块,继续执行后面的代码。 let else 则适用于另一种需求:后面的代码需要匹配得到的变量,匹配失败就退出当前执行路径。 匹配失败不一定代表程序有 bug,也可能只是没有找到值,需要提前返回。

先看已经学过的 match 写法:有值就继续,没有值就返回。

fn print_number(value: Option<i32>) {
    let number = match value {
        Some(n) => n,
        None => return,
    };
    println!("读到 {number}");
}

fn main() {
    print_number(Some(42));
    print_number(None);
}

同一个函数改用 let else:

fn print_number(value: Option<i32>) {
    let Some(number) = value else {
        println!("没有值,结束本次调用");
        return;
    };
    println!("读到 {number}");
}

fn main() {
    print_number(Some(42)); // 读到 42
    print_number(None);     // 打印提示后返回
}

Some(number) 是模式,value 是被检查的值。 当 value 是 Some(42) 时,number 被绑定为 42,可在后续代码中使用。 当 value 是 None 时,执行 else 中的 return,后面的打印不会执行。

if let ... { ... } else { ... } 中,绑定变量只在成功代码块里使用,失败块可以正常结束。 let ... else { ... }; 中,绑定变量供后续代码使用,失败块必须退出当前执行路径。

它的三个价值:

  1. 先检查再继续 —— 成功时取出值,失败时提前返回
  2. “先处理失败,再处理成功” —— 这是所谓的**卫语句(guard clause)**风格, 读起来比“成功路径埋在嵌套里“清楚得多
  3. 变量作用域更自然 —— number 在 else 之后直接可用

else 块必须退出当前执行路径:本节用 return;在循环里也可以用 break 或 continue, 不能只是“什么都不做“。因为编译器需要保证“匹配失败时不会继续往下执行“:

fn check(x: Option<i32>) -> i32 {
    let Some(v) = x else { 0 }; // ← 编译不过:else 没有发散
    v
}

fn main() {}
error[E0308]: `else` clause of `let...else` does not diverge

let else 里的模式通常可能匹配失败,例如 Some(n) 无法匹配 None。 如果模式一定匹配成功,编译器会给出警告:

// no_run:这段**能编译**,只给一个警告(不是错误)
fn main() {
    let x = 5 else { return }; // x 是无可反驳模式,else 永远用不上
}
warning: irrefutable `let...else` pattern
 --> src/main.rs:3:9
  |
3 |     let x = 5 else { return };
  |         ^
  |
  = note: `#[warn(irrefutable_let_patterns)]` on by default

注意这里只给警告,不是错误 —— 因为永远匹配成功的东西写 else 没意义, 但也不至于有害。编译器用警告告诉你“这个 else 是死代码“。

什么时候用哪个:

场景用什么
匹配成功时做一件事,失败时跳过这件事,继续执行if let(不带 else)
后续代码需要匹配得到的变量,失败时退出当前执行路径let else
需要处理多种情况match

let else 在解析、校验、取配置这类代码里特别顺手 —— 第 19 章会结合更多模式再次介绍它。

试一试

  1. 定义 enum Coin { Penny, Nickel, Dime, Quarter },用 match 返回分值。
  2. 给枚举定义一个方法,在方法里通过 match self 处理不同变体。
  3. 写一个接收 Option<i32> 的函数,用 match 分别处理有值与没有值。
  4. 将第 3 题改成 if let ... else,再改成 let ... else,比较变量的作用域。
  5. 判断用户资料、支付结果、任务状态分别适合使用 struct 还是 enum。

下一节:ch07 包、Crate 与模块