Zig by Example
Zig by Example

Switch

< 1 min read

Switch

switch has to be exhaustive — it works on integers, enums, and union tags.

const std = @import("std");

pub fn main() void {
    const n: u8 = 7;

    const desc = switch (n) {
        0 => "zero",
        1, 2, 3 => "small",
        4...9 => "medium", // inclusive range
        10...99 => "large",
        else => "huge",
    };
    std.debug.print("{s}\n", .{desc}); // medium

    // Switch on enum
    const Day = enum { mon, tue, wed, thu, fri, sat, sun };
    const day = Day.sat;

    const kind = switch (day) {
        .sat, .sun => "weekend",
        else => "weekday",
    };
    std.debug.print("{s}\n", .{kind});

    // Switch as expression with capture-conversion
    const val: i32 = switch (n) {
        0...4 => @as(i32, n) * 10,
        else => -1,
    };
    std.debug.print("{d}\n", .{val}); // -1
}
Zig by Example
Zig by Example

by Dariush Abbasi

A hands-on introduction to Zig via annotated examples. Covers the language from Hello World through memory allocation, concurrency, networking, and C interop.

View book →