switch
const std = @import("std");
const builtin = @import("builtin");
const expectEqual = std.testing.expectEqual;
test "switch simple" {
const a: u64 = 10;
const zz: u64 = 103;
// switch 表达式的全部分支都必须能够强制转换为
// 同一种公共类型。
//
// 分支不能贯穿。如果需要贯穿行为,应合并
// 匹配项并使用 if。
const b = switch (a) {
// 可以通过 ',' 合并多个匹配项
1, 2, 3 => 0,
// 可以使用 ... 语法指定范围,范围包含
// 两端的值。
5...100 => 1,
// 分支可以任意复杂。
101 => blk: {
const c: u64 = 5;
break :blk c * 2 + 1;
},
// 允许匹配任意表达式,前提是
// 表达式在编译时已知。
zz => zz,
blk: {
const d: u32 = 5;
const e: u32 = 100;
break :blk d + e;
} => 107,
// else 分支匹配此前未捕获的所有值。
// 除非已处理整个值域,
// 否则必须提供 else 分支。
else => 9,
};
try expectEqual(1, b);
}
// switch 表达式也可以用于函数外部:
const os_msg = switch (builtin.target.os.tag) {
.linux => "we found a linux user",
else => "not a linux user",
};
// 函数内部,如果目标表达式在编译时已知,
// switch 语句就会隐式在编译时求值。
test "switch inside function" {
switch (builtin.target.os.tag) {
.fuchsia => {
// 在 fuchsia 以外的操作系统中,甚至不会分析此块,
// 因此不会触发这条编译错误。
// 在 fuchsia 上则会触发这条编译错误。
@compileError("fuchsia not supported");
},
else => {},
}
}$ zig test test_switch.zig
1/2 test_switch.test.switch simple...OK
2/2 test_switch.test.switch inside function...OK
All 2 tests passed.
switch 可以捕获标记联合的字段值。在捕获变量名称前加上 *,将其变为指针,即可修改字段值。
const expectEqual = @import("std").testing.expectEqual;
test "switch on tagged union" {
const Point = struct {
x: u8,
y: u8,
};
const Item = union(enum) {
a: u32,
c: Point,
d,
e: u32,
};
var a = Item{ .c = Point{ .x = 1, .y = 2 } };
// 允许匹配更复杂的枚举。
const b = switch (a) {
// 匹配时可以使用捕获组,返回匹配到的枚举
// 值。如果两个匹配项的载荷类型相同,
// 可以把它们放在同一个 switch 分支中。
Item.a, Item.e => |item| item,
// 可以使用 `*` 语法获取匹配值的引用。
Item.c => |*item| blk: {
item.*.x += 1;
break :blk 6;
},
// 如果已穷尽处理所有类型情况,就不需要 else
Item.d => 8,
};
try expectEqual(6, b);
try expectEqual(2, a.c.x);
}$ zig test test_switch_tagged_union.zig
1/1 test_switch_tagged_union.test.switch on tagged union...OK
All 1 tests passed.
另见:
穷尽匹配
switch 表达式没有 else 子句时,必须穷尽列出全部可能的值,否则产生编译错误:
const Color = enum {
auto,
off,
on,
};
test "exhaustive switching" {
const color = Color.off;
switch (color) {
Color.auto => {},
Color.on => {},
}
}$ zig test test_unhandled_enumeration_value.zig
/home/alexrp/Sources/ziglang/zig/doc/langref/test_unhandled_enumeration_value.zig:9:5: error: switch must handle all possibilities
switch (color) {
^~~~~~
/home/alexrp/Sources/ziglang/zig/doc/langref/test_unhandled_enumeration_value.zig:3:5: note: unhandled enumeration value: 'off'
off,
^~~
/home/alexrp/Sources/ziglang/zig/doc/langref/test_unhandled_enumeration_value.zig:1:15: note: enum 'test_unhandled_enumeration_value.Color' declared here
const Color = enum {
^~~~
使用枚举字面量进行匹配
将枚举字面量与 switch 结合使用,可以避免重复指定 enum 或 union 类型:
const std = @import("std");
const expect = std.testing.expect;
const Color = enum {
auto,
off,
on,
};
test "enum literals with switch" {
const color = Color.off;
const result = switch (color) {
.auto => false,
.on => false,
.off => true,
};
try expect(result);
}$ zig test test_exhaustive_switch.zig
1/1 test_exhaustive_switch.test.enum literals with switch...OK
All 1 tests passed.
匹配错误
匹配错误时,允许一些特殊情况,以简化泛型编程模式:
const FileOpenError0 = error{
AccessDenied,
OutOfMemory,
FileNotFound,
};
fn openFile0() FileOpenError0 {
return error.OutOfMemory;
}
test "unreachable else prong" {
switch (openFile0()) {
error.AccessDenied, error.FileNotFound => |e| return e,
error.OutOfMemory => {},
// 'openFile0' 不会返回其他错误,因此编译时可知
// 'else' 分支不可达。不过在这种情况下,添加该分支
// 不会产生“不可达的 else 分支”编译错误:
else => unreachable,
}
// 允许的不可达 else 分支有:
// `else => unreachable,`
// `else => return,`
// `else => |e| return e,`(其中 `e` 是任意标识符)
}
const FileOpenError1 = error{
AccessDenied,
SystemResources,
FileNotFound,
};
fn openFile1() FileOpenError1 {
return error.SystemResources;
}
fn openFileGeneric(comptime kind: u1) switch (kind) {
0 => FileOpenError0,
1 => FileOpenError1,
} {
return switch (kind) {
0 => openFile0(),
1 => openFile1(),
};
}
test "comptime unreachable errors not in error set" {
switch (openFileGeneric(1)) {
error.AccessDenied, error.FileNotFound => |e| return e,
error.OutOfMemory => comptime unreachable, // 不属于 `FileOpenError1`!
error.SystemResources => {},
}
}$ zig test test_switch_on_errors.zig
1/2 test_switch_on_errors.test.unreachable else prong...OK
2/2 test_switch_on_errors.test.comptime unreachable errors not in error set...OK
All 2 tests passed.
带标签的 switch
为 switch 语句添加标签后,可以通过 break 或 continue 引用它。break 会从 switch 返回一个值。
以 switch 为目标的 continue 必须带有操作数。执行时会跳转到匹配的分支,相当于用 continue 的操作数替换初始匹配值后重新执行 switch。
const std = @import("std");
test "switch continue" {
sw: switch (@as(i32, 5)) {
5 => continue :sw 4,
// 单个 switch 分支内部可以出现多次 `continue`。
2...4 => |v| {
if (v > 3) {
continue :sw 2;
} else if (v == 3) {
// `break` 可以指向带标签的循环。
break :sw;
}
continue :sw 1;
},
1 => return,
else => unreachable,
}
}$ zig test test_switch_continue.zig
1/1 test_switch_continue.test.switch continue...OK
All 1 tests passed.
从语义上说,这等价于以下循环:
const std = @import("std");
test "switch continue, equivalent loop" {
var sw: i32 = 5;
while (true) {
switch (sw) {
5 => {
sw = 4;
continue;
},
2...4 => |v| {
if (v > 3) {
sw = 2;
continue;
} else if (v == 3) {
break;
}
sw = 1;
continue;
},
1 => return,
else => unreachable,
}
}
}$ zig test test_switch_continue_equivalent.zig
1/1 test_switch_continue_equivalent.test.switch continue, equivalent loop...OK
All 1 tests passed.
这可以提高状态机等代码的清晰度,因为语法 continue :sw .next_state 无歧义、含义明确且易于理解。
不过,最初的动机是需要对数组的每个元素执行匹配;此时单个 switch 能同时改善可读性和性能:
const std = @import("std");
const expectEqual = std.testing.expectEqual;
const Instruction = enum {
add,
mul,
end,
};
fn evaluate(initial_stack: []const i32, code: []const Instruction) !i32 {
var buffer: [8]i32 = undefined;
var stack = std.ArrayList(i32).initBuffer(&buffer);
try stack.appendSliceBounded(initial_stack);
var ip: usize = 0;
return vm: switch (code[ip]) {
// `continue` 之后的所有代码均不可达,因此此分支
// 不提供结果。
.add => {
try stack.appendBounded(stack.pop().? + stack.pop().?);
ip += 1;
continue :vm code[ip];
},
.mul => {
try stack.appendBounded(stack.pop().? * stack.pop().?);
ip += 1;
continue :vm code[ip];
},
.end => stack.pop().?,
};
}
test "evaluate" {
const result = try evaluate(&.{ 7, 2, -3 }, &.{ .mul, .add, .end });
try expectEqual(1, result);
}$ zig test test_switch_dispatch_loop.zig
1/1 test_switch_dispatch_loop.test.evaluate...OK
All 1 tests passed.
如果 continue 的操作数在编译时已知,就可以将其降低为无条件跳转到对应分支。这种跳转可以被完全预测,因此执行通常很快。
操作数在运行时已知时,每个 continue 都可以内嵌条件分支(理想情况下通过跳转表实现),让 CPU 独立预测其目标,而不受其他分支影响。降低为循环则会迫使所有分支经过相同的分派点,妨碍分支预测。
内联 switch 分支
switch 分支可以标记为 inline,针对每个可能值生成一份分支体,使捕获值成为编译时值。
const std = @import("std");
const expect = std.testing.expect;
const expectError = std.testing.expectError;
fn isFieldOptional(comptime T: type, field_index: usize) !bool {
const field_types = @typeInfo(T).@"struct".field_types;
return switch (field_index) {
// 此分支会分析两次,每次的 `idx` 都是
// 编译时已知值。
inline 0, 1 => |idx| @typeInfo(field_types[idx]) == .optional,
else => return error.IndexOutOfBounds,
};
}
const Struct1 = struct { a: u32, b: ?u32 };
test "using @typeInfo with runtime values" {
var index: usize = 0;
try expect(!try isFieldOptional(Struct1, index));
index += 1;
try expect(try isFieldOptional(Struct1, index));
index += 1;
try expectError(error.IndexOutOfBounds, isFieldOptional(Struct1, index));
}
// 对 `Struct1` 调用 `isFieldOptional` 会展开为
// 与以下函数等价的代码:
fn isFieldOptionalUnrolled(field_index: usize) !bool {
return switch (field_index) {
0 => false,
1 => true,
else => return error.IndexOutOfBounds,
};
}$ zig test test_inline_switch.zig
1/1 test_inline_switch.test.using @typeInfo with runtime values...OK
All 1 tests passed.
inline 关键字也可以与范围结合使用:
fn isFieldOptional(comptime T: type, field_index: usize) !bool {
const field_types = @typeInfo(T).@"struct".field_types;
return switch (field_index) {
inline 0...field_types.len - 1 => |idx| @typeInfo(field_types[idx]) == .optional,
else => return error.IndexOutOfBounds,
};
}inline else 分支可以作为 inline for 循环的一种类型安全替代方案:
const std = @import("std");
const expectEqual = std.testing.expectEqual;
const SliceTypeA = extern struct {
len: usize,
ptr: [*]u32,
};
const SliceTypeB = extern struct {
ptr: [*]SliceTypeA,
len: usize,
};
const AnySlice = union(enum(u8)) {
a: SliceTypeA,
b: SliceTypeB,
c: []const u8,
d: []AnySlice,
};
fn withFor(any: AnySlice) usize {
const Tag = @typeInfo(AnySlice).@"union".tag_type.?;
const info = @typeInfo(Tag).@"enum";
inline for (info.field_names, info.field_values) |field_name, field_value| {
// 使用 `inline for` 时,函数生成为
// 一系列 `if` 语句,并依靠优化器
// 将它们转换为 switch。
if (field_value == @backingInt(any)) {
return @field(any, field_name).len;
}
}
// 使用 `inline for` 时,编译器不知道所有
// 可能情况都已处理,因此必须显式写出 `unreachable`。
unreachable;
}
fn withSwitch(any: AnySlice) usize {
return switch (any) {
// 使用 `inline else` 时,函数会显式生成为
// 所需的 switch,编译器能够检查
// 是否已处理每一种可能情况。
inline else => |slice| slice.len,
};
}
test "inline for and inline else similarity" {
const any = AnySlice{ .c = "hello" };
try expectEqual(5, withFor(any));
try expectEqual(5, withSwitch(any));
}$ zig test test_inline_else.zig
1/1 test_inline_else.test.inline for and inline else similarity...OK
All 1 tests passed.
对联合使用内联匹配分支时,即使载荷仅在运行时已知,也可以通过额外捕获在编译时获取联合的枚举标记值。
const std = @import("std");
const expectEqual = std.testing.expectEqual;
const U = union(enum) {
a: u32,
b: f32,
};
fn getNum(u: U) u32 {
switch (u) {
// 此处 `num` 是运行时已知值,为 `u.a`
// 或 `u.b`;`tag` 则是 `u` 在编译时已知的标记值。
inline else => |num, tag| {
if (tag == .b) {
return @intFromFloat(num);
}
return num;
},
}
}
test "test" {
const u = U{ .b = 42 };
try expectEqual(42, getNum(u));
}$ zig test test_inline_switch_union_tag.zig
1/1 test_inline_switch_union_tag.test.test...OK
All 1 tests passed.
另见: