typestar

Optionals in Zig

?u32 is a berth number or null, and the compiler will not let you forget which.

const std = @import("std");

fn findBerth(ship: []const u8) ?u32 {
    if (std.mem.eql(u8, ship, "Persephone")) return 9;
    return null;
}

pub fn main() void {
    // ?u32 holds a number or null; if unwraps it by capture.
    if (findBerth("Persephone")) |berth| {
        std.debug.print("moor at berth {d}\n", .{berth});
    }

    // orelse supplies the value for the null case.
    const anchorage = findBerth("Dreadnought") orelse 0;
    std.debug.print("unknown ships anchor at {d}\n", .{anchorage});
}

How it works

  1. ?u32 in the return type admits null as an honest answer.
  2. if (findBerth(...)) |berth| unwraps by capture only when a value exists.
  3. orelse 0 supplies the anchorage for ships the harbor does not know.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
471
Tokens
117
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 100 seconds.

Type this snippet

Step 1 of 3 in Optionals & pointers, step 10 of 27 in Language basics.

← Previous Next →

Optionals in other languages