PAYATHON 2026

Zig 中如何用 unreachable 补全 switch

数据小陈

明确结论

在 switch (op) 的最后加上一行:

else => unreachable,

op 的类型是 u8,Zig 编译器要求 switch 覆盖 u8 的所有可能取值,else 就是负责兜底的那个分支。写 unreachable 表示你认为运行时不会出现 1、2、3 以外的值。

完整示例

const std = @import("std");

pub fn main() void {
    const operations = [_]u8{ 1, 1, 1, 3, 2, 2 };

    var current_value: u32 = 0;

    for (operations) |op| {
        switch (op) {
            1 => {
                current_value += 1;
            },
            2 => {
                current_value -= 1;
            },
            3 => {
                current_value *= current_value;
            },
            else => unreachable,
        }
    }
}

你贴的代码片段结尾少了 for 和 main 的闭合花括号,上面的示例补上了这些结构,关键还是 switch 的写法。

为什么需要 else => unreachable

operations 的元素类型是 [_]u8,因此 op 是 u8。数组里实际只放了 1、2、3,但类型系统并不知道“只可能是这三个值”。Zig 对整数类型的 switch 要求覆盖所有可能值,否则就得提供 else 分支。加上 else => unreachable, 之后:

  • 编译器认为 switch 已经完备;
  • 运行时如果真的出现其他值,会进入 unreachable;
  • Debug 和 ReleaseSafe 模式下,触发 unreachable 一般会 panic,数据出错时比较容易发现;
  • ReleaseFast、ReleaseSmall 这类模式下,unreachable 只是“不可能发生”的承诺,真触发了行为不可依赖。

所以只有在你确实能保证 op 不会出现 1、2、3 之外的值时,才这样写。

可选做法:用 enum 限定取值

如果这些操作本来就是一个固定集合,改成 enum 会更稳妥:

const std = @import("std");

const Operation = enum {
    increment,
    decrement,
    square,
};

pub fn main() void {
    const operations = [_]Operation{
        .increment,
        .increment,
        .increment,
        .square,
        .decrement,
        .decrement,
    };

    var current_value: u32 = 0;

    for (operations) |op| {
        switch (op) {
            .increment => {
                current_value += 1;
            },
            .decrement => {
                current_value -= 1;
            },
            .square => {
                current_value *= current_value;
            },
        }
    }
}

这种写法不需要 else,因为 enum 的取值集合在类型层面就是固定的,switch 覆盖所有枚举成员即可。

注意事项

  • else => unreachable, 末尾是逗号,不是分号,它是 switch 的一个分支。
  • 别为了“能编译过”写成 else => {},那会把非法操作静默忽略掉,问题只是往后拖到了逻辑层。
  • 如果以后操作码可能扩展,优先考虑用 enum,或者显式处理未知值,不要长期依赖 unreachable。
  • 原代码里 current_value 是 u32,current_value -= 1 在安全模式下可能因下溢 panic;示例数据不会触发,但真实输入要保证不会从 0 减 1。

备注:内容仅供参考。