Zig Switch
A switch statement compares one value against a list of choices and runs the matching branch. It is a clean way to handle many exact values at once.
Switch picks the prong that matches the value
The day number is 3. Switch compares it with each prong and picks the matching name.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const day: i32 = 3;
const name = switch (day) {
1 => "Mon",
2 => "Tue",
3 => "Wed",
else => "Other",
};
try out.print("{s}\n", .{name});
}
A prong can match a whole range
Ranges let one prong cover many scores. The score 85 falls in the 80...89 range.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const score: i32 = 85;
const grade: u8 = switch (score) {
90...100 => 'A',
80...89 => 'B',
70...79 => 'C',
else => 'F',
};
try out.print("{c}\n", .{grade});
}
One prong can list several values
Commas put several values on one prong. The number 4 is one of the listed values, so that prong wins.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const n: i32 = 4;
const label = switch (n) {
2, 4, 6 => "small even",
else => "other",
};
try out.print("{s}\n", .{label});
}
Example
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const day: i32 = 6;
const kind = switch (day) {
1...5 => "weekday",
6, 7 => "weekend",
else => "invalid",
};
try out.print("day {d}: {s}\n", .{ day, kind });
}
Key points
- Value: switch takes one value in parentheses and tests it against each choice.
- Prong: each choice is a prong, written as a value, an arrow, and then its result.
- Ranges: a prong can cover a whole range of values, such as 80...89.
- Multiple values: one prong can list several values separated by commas.
- Else: the else prong runs when no other prong matches the value.
- Expression: a switch can produce a value, so its result can be stored in a const.
In this example, day is 6. The range prong 1...5 does not match, the next prong lists 6 and 7, so kind stores weekend and the print shows day 6 as a weekend day.
Note
Zig switch has no fall-through, so a match never spills into the next prong.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A switch grades a score with prongs 90...100 for A, 80...89 for B, 70...79 for C, and else for F. Which grade does a score of 72 get?