Switch 语句 (switch)

switch 表达式用于根据值的不同情况执行不同的代码分支。它必须是穷尽的(exhaustive),这意味着必须处理所有可能的值。

基本用法

const std = @import("std");

fn test_switch(x: i8) void {
    switch (x) {
        -1...1 => {
            std.debug.print("大约是零\n", .{});
        },
        10, 100 => {
            std.debug.print("是 10 或 100\n", .{});
        },
        else => {
            std.debug.print("其他值\n", .{});
        },
    }
}

作为表达式

switch 可以作为表达式使用,返回一个值。所有分支必须返回相同类型的值。

const x: i8 = 10;
const y = switch (x) {
    0 => 0,
    1 => 1,
    else => 10,
};

范围匹配

使用 ... 运算符可以匹配一个包含范围(inclusive range)。

switch (x) {
    0...10 => {}, // 匹配 0 到 10(含)
    else => {},
}

标签 switch (Labeled Switch)

switch 可以在 inline 循环(如 inline forinline while)内部使用,以在编译时生成代码。

另请参阅: