TExcelTAD
Home › Zig › Zig Switch

Zig Switch

switch picks one branch out of many based on a value. Zig's switch is far stricter — and far more useful — than C's: it is an expression, branches never fall through, and the compiler checks that every possible value is handled.

Basic switch

zig · try it yourself
const std = @import("std");

pub fn main() void {
    const day: u8 = 6;
    const name = switch (day) {
        1 => "Monday",
        2 => "Tuesday",
        3 => "Wednesday",
        4 => "Thursday",
        5 => "Friday",
        6, 7 => "Weekend",
        else => "invalid",
    };
    std.debug.print("day {d}: {s}\n", .{ day, name });
}
day 6: Weekend
Syntax Meaning
1 => … a single value
6, 7 => … several values share a branch
10...19 => … an inclusive range (three dots)
else => … everything not listed

Exhaustiveness

A u8 has 256 possible values. If you list only some and leave out else, the program does not compile:

zig
const std = @import("std");

pub fn main() void {
    const level: u8 = 2;
    const label = switch (level) {
        1 => "low",
        2 => "medium",
        3 => "high",
    };
    std.debug.print("{s}\n", .{label});
}
text
./example.zig:5:19: error: switch must handle all possibilities
    const label = switch (level) {
                  ^~~~~~

With enums (next chapters), exhaustiveness becomes a superpower: add a new enum member and the compiler points at every switch that forgot to handle it.

Ranges and blocks

Branches can be whole blocks. A block that should produce a value uses a label and break :label value (explained in the next lesson), but a block that only performs actions needs no label:

zig · try it yourself
const std = @import("std");

pub fn main() void {
    const scores = [_]u8{ 95, 82, 67, 40, 100 };
    for (scores) |s| {
        const grade: u8 = switch (s) {
            90...100 => 'A',
            75...89 => 'B',
            50...74 => 'C',
            else => 'F',
        };
        switch (grade) {
            'A' => {
                std.debug.print("{d}: {c} - excellent!\n", .{ s, grade });
            },
            'F' => std.debug.print("{d}: {c} - try again\n", .{ s, grade }),
            else => std.debug.print("{d}: {c}\n", .{ s, grade }),
        }
    }
}
95: A - excellent!
82: B
67: C
40: F - try again
100: A - excellent!

Switching on characters and enums

Characters are just u8 values, so they work naturally. Enums are switched using their tag names with a leading dot:

zig · try it yourself
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 {
    const lights = [_]Light{ .green, .yellow, .red };
    for (lights) |l| std.debug.print("{t}: {s}\n", .{ l, advice(l) });

    var vowels: u32 = 0;
    for ("programming in zig") |c| {
        switch (c) {
            'a', 'e', 'i', 'o', 'u' => vowels += 1,
            else => {},
        }
    }
    std.debug.print("vowels: {d}\n", .{vowels});
}
green: go
yellow: slow down
red: stop
vowels: 5

else => {} is how you say "do nothing for all other values" explicitly.

Switching on strings?

Not directly — strings are slices, and switch needs values comparable at compile time. Common workarounds are a chain of if (std.mem.eql(…)), or converting the string to an enum with std.meta.stringToEnum:

zig
const Command = enum { start, stop, status };
const cmd = std.meta.stringToEnum(Command, "stop") orelse return;
switch (cmd) {
    .start => …,
    .stop => …,
    .status => …,
}

Capturing the switched value

When a branch covers several values or a range, you can capture which value matched:

zig
switch (code) {
    200...299 => |ok| std.debug.print("success {d}\n", .{ok}),
    else => |other| std.debug.print("status {d}\n", .{other}),
}

Captures become much more important with tagged unions, where they give you the data stored in the active variant.

Test yourself

What does 10...20 mean in a switch branch?

  1. 10 to 19
  2. 10 to 20 inclusive
  3. 11 to 19
  4. A slice

What happens if a switch on a u8 lists some values and has no else?

  1. Unmatched values do nothing
  2. The program panics
  3. Compile error: switch must handle all possibilities
  4. The first branch is used

Does a Zig switch branch fall through to the next one?

  1. Yes, unless you write break
  2. No, never
  3. Only for ranges
  4. Only in Debug mode