Lesson contents

Choose from several cases

Check a value against several choices. Give it a default result for anything outside the listed cases.

Simple example

Choose the second price.

Start2
Result4
lesson.zig
const std = @import("std");

pub fn main() !void {
    const price: i64 = switch (@as(i64, 2)) { 1 => 2, 2 => 4, else => 6 };
    std.debug.print("{any}\n", .{price});
}
Output
4
Advertisements

Everyday examples

The bus charges 2 coins in zone 1, 4 in zone 2 and 6 in the other zones. What is the fare in zone 3?

StartZone 3
Result6
lesson.zig
const std = @import("std");

pub fn main() !void {
    const price: i64 = switch (@as(i64, 3)) { 1 => 2, 2 => 4, else => 6 };
    std.debug.print("{any}\n", .{price});
}
Output
6
Run the example
Terminal
zig run lesson.zig
Official documentation