Zig Switch
When one value can lead to many different paths, a long if ... else if ... else if chain gets hard to read. switch is the tidy version: you list the possible values, and Zig runs the branch that matches. If you know switch from C, the good news is that Zig’s has no fall-through and no break to forget. It also checks that you’ve handled every possible value, which turns out to be one of its most useful features.
A first switch
Section titled “A first switch”You give switch a value in parentheses, then list prongs: a value, a fat arrow =>, and what to do. Each prong ends with a comma:
const std = @import("std");
fn sayDay(day: u8) void { switch (day) { 1 => std.debug.print("{d}: Monday\n", .{day}), 2 => std.debug.print("{d}: Tuesday\n", .{day}), 3 => std.debug.print("{d}: Wednesday\n", .{day}), else => std.debug.print("{d}: some other day\n", .{day}), }}
pub fn main() void { sayDay(2); sayDay(3); sayDay(6);}Output:
2: Tuesday3: Wednesday6: some other dayfn sayDay(day: u8) void is a small function so we can try several values; you’ll learn functions in Zig Functions. Zig compares day with each prong from top to bottom, runs the one that matches, and then it’s done. else catches every value you didn’t list.
Several values in one prong
Section titled “Several values in one prong”If several values should do the same thing, list them in one prong with commas:
const std = @import("std");
fn dayType(day: u8) void { switch (day) { 1, 2, 3, 4, 5 => std.debug.print("{d}: weekday\n", .{day}), 6, 7 => std.debug.print("{d}: weekend\n", .{day}), else => std.debug.print("{d}: not a day\n", .{day}), }}
pub fn main() void { dayType(3); dayType(7); dayType(12);}Output:
3: weekday7: weekend12: not a dayThis is what you’d do in C by stacking case 6: case 7: on top of each other.
Ranges with ...
Section titled “Ranges with ...”For a run of numbers, write a range with three dots. 1...5 means 1, 2, 3, 4 and 5: both ends are included. Ranges work for characters too, because a character like 'a' is just a u8 number:
const std = @import("std");
pub fn main() void { const text = "Zig 0.17, hi!"; var letters: u32 = 0; var digits: u32 = 0; var others: u32 = 0;
for (text) |c| { switch (c) { 'a'...'z', 'A'...'Z' => letters += 1, '0'...'9' => digits += 1, else => others += 1, } }
std.debug.print("letters: {d}, digits: {d}, others: {d}\n", .{ letters, digits, others });}Output:
letters: 5, digits: 3, others: 5for (text) |c| goes through the string one character at a time (you’ll meet it properly in Zig For). The first prong mixes two ranges with a comma, so it matches lowercase and uppercase letters.
Prongs with more than one line
Section titled “Prongs with more than one line”When a prong needs to do several things, give it a block in curly braces:
const std = @import("std");
pub fn main() void { const level: u8 = 3;
switch (level) { 1 => std.debug.print("Easy mode\n", .{}), 2, 3 => { std.debug.print("Normal mode\n", .{}); std.debug.print("Enemies hit a little harder.\n", .{}); }, else => {}, }}Output:
Normal modeEnemies hit a little harder.else => {} means “for anything else, do nothing”. An empty block is a perfectly fine prong.
switch as an expression
Section titled “switch as an expression”Just like if, a switch can produce a value. Each prong gives a value instead of doing something, and you store the result:
const std = @import("std");
fn grade(score: u8) u8 { const letter: u8 = switch (score) { 90...100 => 'A', 70...89 => 'B', 50...69 => 'C', else => 'F', }; return letter;}
pub fn main() void { std.debug.print("95 -> {c}\n", .{grade(95)}); std.debug.print("72 -> {c}\n", .{grade(72)}); std.debug.print("40 -> {c}\n", .{grade(40)});}Output:
95 -> A72 -> B40 -> FAll prongs must give the same kind of value, here a u8 character.
Every value must be handled
Section titled “Every value must be handled”A Zig switch must be exhaustive: every possible value of the type needs a prong. Leave some out, with no else, and the program doesn’t compile:
const std = @import("std");
fn size(n: u8) void { switch (n) { 0 => std.debug.print("none\n", .{}), 1...9 => std.debug.print("a few\n", .{}), }}
pub fn main() void { size(4);}main.zig:4:5: error: switch must handle all possibilities switch (n) { ^~~~~~A u8 can be anything from 0 to 255, and values 10 to 255 have no prong. Adding else => std.debug.print("lots\n", .{}), fixes it.
This check really pays off with enums. An enum is a type with a fixed list of named values; you’ll meet them properly in Zig Enums. Because the list is fixed, you can handle every value and skip else entirely. You can write each value with a leading dot, like .red, since Zig already knows the type:
const std = @import("std");
const Light = enum { red, yellow, green };
fn advice(light: Light) []const u8 { return switch (light) { .red => "stop", .yellow => "slow down", .green => "go", };}
pub fn main() void { std.debug.print("red: {s}\n", .{advice(.red)}); std.debug.print("green: {s}\n", .{advice(.green)});}Output:
red: stopgreen: goNow imagine you forget a value, or someone adds a new color to Light next month. The compiler points at the exact one you missed:
const std = @import("std");
const Light = enum { red, yellow, green };
fn advice(light: Light) []const u8 { return switch (light) { .red => "stop", .green => "go", };}
pub fn main() void { std.debug.print("{s}\n", .{advice(.red)});}main.zig:6:12: error: switch must handle all possibilities return switch (light) { ^~~~~~main.zig:3:27: note: unhandled enumeration value: 'yellow'const Light = enum { red, yellow, green }; ^~~~~~Zig also goes the other way: if you’ve already covered every value, an else prong is an error, because it could never run:
const std = @import("std");
pub fn main() void { const bits: u2 = 3; const name = switch (bits) { 0 => "zero", 1 => "one", 2 => "two", 3 => "three", else => "?", }; std.debug.print("{s}\n", .{name});}main.zig:10:14: error: unreachable else prong; all cases already handled else => "?", ~~~~~^~~~~~A u2 only holds 0 to 3, so the four prongs already cover it. Delete the else line and it works. The language reference on exhaustive switching has the full rules.
Zig also catches values that appear twice, for example a 4 prong after a 1...5 prong: that’s error: duplicate switch value.
Capturing the matched value
Section titled “Capturing the matched value”A prong can capture the value it matched with |name|. This is most useful with ranges and else, where you don’t know the exact value in advance:
const std = @import("std");
fn check(n: u8) void { switch (n) { 0 => std.debug.print("zero\n", .{}), 1...9 => |small| std.debug.print("{d} is one digit\n", .{small}), else => |big| std.debug.print("{d} has more digits\n", .{big}), }}
pub fn main() void { check(0); check(7); check(42);}Output:
zero7 is one digit42 has more digitsHere small and big are just n again, so you could use n instead. Captures become really important with tagged unions, where each prong can pull out a different kind of data. That’s in Zig Tagged Unions.
You can’t switch on strings
Section titled “You can’t switch on strings”Coming from JavaScript, C# or Go, you might try switch on a piece of text. Zig doesn’t allow it:
const std = @import("std");
pub fn main() void { const command: []const u8 = "start"; switch (command) { "start" => std.debug.print("Starting\n", .{}), else => std.debug.print("Unknown\n", .{}), }}main.zig:6:9: error: cannot switch on strings "start" => std.debug.print("Starting\n", .{}), ^~~~~~~A string in Zig is a slice of bytes, and comparing two slices means checking every byte, which switch won’t hide from you. Use an if chain with std.mem.eql, which compares two slices:
const std = @import("std");
pub fn main() void { const command: []const u8 = "stop";
if (std.mem.eql(u8, command, "start")) { std.debug.print("Starting\n", .{}); } else if (std.mem.eql(u8, command, "stop")) { std.debug.print("Stopping\n", .{}); } else { std.debug.print("Unknown command\n", .{}); }}Output:
StoppingLabeled switch: jumping between prongs
Section titled “Labeled switch: jumping between prongs”This one is a bit more advanced, so feel free to skim it now and come back later. You can put a label in front of a switch (a name and a colon, like state:). Inside a prong, continue :state value jumps back to the top of that switch as if it had been called with the new value. It’s a clean way to write a state machine, a program that moves from one state to the next:
const std = @import("std");
const State = enum { idle, running, finished };
pub fn main() void { var ticks: u32 = 0;
state: switch (State.idle) { .idle => { std.debug.print("idle, starting up\n", .{}); continue :state .running; }, .running => { ticks += 1; std.debug.print("running, tick {d}\n", .{ticks}); if (ticks < 3) continue :state .running; continue :state .finished; }, .finished => std.debug.print("finished after {d} ticks\n", .{ticks}), }}Output:
idle, starting uprunning, tick 1running, tick 2running, tick 3finished after 3 ticksThe switch starts with .idle, which jumps to .running. That prong runs three times, then jumps to .finished, which doesn’t continue, so the switch ends. You could write the same thing with a while loop and a state variable; the language reference on labeled switch shows both side by side. Labels on loops and blocks get their own lessons: Zig Break/Continue and Zig Blocks.
Practice
Section titled “Practice”1. Vowel or not
Section titled “1. Vowel or not”Write a function that takes a lowercase letter (u8) and prints whether it’s a vowel. Try 'e', 'z' and 'o'.
Hint: one prong with five values, plus else.
Show solution
const std = @import("std");
fn vowelCheck(c: u8) void { switch (c) { 'a', 'e', 'i', 'o', 'u' => std.debug.print("{c} is a vowel\n", .{c}), else => std.debug.print("{c} is not a vowel\n", .{c}), }}
pub fn main() void { vowelCheck('e'); vowelCheck('z'); vowelCheck('o');}Output:
e is a vowelz is not a vowelo is a vowelA comma-separated list in one prong matches any of those values.
2. HTTP status classes
Section titled “2. HTTP status classes”Write fn statusClass(code: u16) []const u8 that returns "success" for 200 to 299, "redirect" for 300 to 399, "client error" for 400 to 499, "server error" for 500 to 599, and "unknown" for anything else. Use a switch expression and print the result for 200, 404 and 503.
Hint: return switch (code) { 200...299 => "success", ... };
Show solution
const std = @import("std");
fn statusClass(code: u16) []const u8 { return switch (code) { 200...299 => "success", 300...399 => "redirect", 400...499 => "client error", 500...599 => "server error", else => "unknown", };}
pub fn main() void { std.debug.print("200: {s}\n", .{statusClass(200)}); std.debug.print("404: {s}\n", .{statusClass(404)}); std.debug.print("503: {s}\n", .{statusClass(503)});}Output:
200: success404: client error503: server errorThe return type []const u8 tells Zig what every prong produces, so no extra type annotation is needed here.
3. Fix the missing case
Section titled “3. Fix the missing case”This code doesn’t compile. Make it print .circle has 0 corners and .square has 4 corners without adding an else.
const std = @import("std");
const Shape = enum { circle, triangle, square };
fn corners(shape: Shape) u8 { return switch (shape) { .circle => 0, .square => 4, };}
pub fn main() void { std.debug.print(".circle has {d} corners\n", .{corners(.circle)}); std.debug.print(".square has {d} corners\n", .{corners(.square)});}Hint: read the error’s note: line. Which value is unhandled?
Show solution
const std = @import("std");
const Shape = enum { circle, triangle, square };
fn corners(shape: Shape) u8 { return switch (shape) { .circle => 0, .triangle => 3, .square => 4, };}
pub fn main() void { std.debug.print(".circle has {d} corners\n", .{corners(.circle)}); std.debug.print(".square has {d} corners\n", .{corners(.square)});}Output:
.circle has 0 corners.square has 4 cornersThe compiler’s note says unhandled enumeration value: 'triangle'. Adding that prong makes the switch exhaustive, and if you add a hexagon to Shape later, you’ll get the same helpful error again.
switch (value) { a => ..., b => ..., else => ... }runs exactly one prong. There’s no fall-through and nobreak.- One prong can match several values (
6, 7 =>) or a range (1...5 =>, both ends included). switchis an expression:const x: u8 = switch (n) { ... };. Give number results a type.- A
switchmust be exhaustive. With enums, list every value and skipelse, so new values cause a compile error. |v|captures the matched value. You can’t switch on strings: usestd.mem.eqlor turn the text into an enum.- A labeled switch with
continue :label valuejumps between prongs, which is handy for state machines.
Next up: Zig While, the loop that keeps going as long as a condition is true.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: switch: every
switchfeature, including tagged unions and inline prongs. - Zig language reference: exhaustive switching: why a missing enum value is a compile error.
- Zig language reference: labeled switch:
continue :labeland how it compares to a loop. - Ziglings: small exercises to fix, including several on
switch.