switch
Shell
1/2 test "switch simple"... OK
2/2 test "switch inside function"... OK
All 2 tests passed.
switch
can be used to capture the field values of a . Modifications to the field values can be done by placing a *
before the capture variable name, turning it into a pointer.
test_switch_tagged_union.zig
$ zig test test_switch_tagged_union.zig
All 1 tests passed.
See also:
When a switch
expression does not have an else
clause, it must exhaustively list all the possible values. Failure to do so is a compile error:
test.zig
$ zig test test.zig
./docgen_tmp/test.zig:9:5: error: enumeration value 'Color.off' not handled in switch
./docgen_tmp/test.zig:7:29: note: referenced here
test "exhaustive switching" {
^
Enum Literals can be useful to use with switch
to avoid repetitively specifying or union types:
test_exhaustive_switch.zig
Shell
$ zig test test_exhaustive_switch.zig
1/1 test "enum literals with switch"... OK