typestar

Errors and try in Zig

Errors are values in the return type: a vault that either opens or says why not.

const std = @import("std");

const VaultError = error{WrongCombination};

fn open(guess: u32) VaultError![]const u8 {
    if (guess == 628) return "deed to the tin mine";
    return VaultError.WrongCombination;
}

pub fn main() !void {
    // try unwraps a success or returns the error to the caller.
    const prize = try open(628);
    std.debug.print("inside: {s}\n", .{prize});
    // if with an else-capture inspects the failure instead.
    if (open(111)) |p| {
        std.debug.print("inside: {s}\n", .{p});
    } else |err| {
        std.debug.print("no luck: {s}\n", .{@errorName(err)});
    }
}

How it works

  1. error{WrongCombination} declares the error set; ! puts it in the return type.
  2. try open(628) unwraps success or returns the error up the stack.
  3. if (...) |p| ... else |err| captures whichever side actually happened.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
553
Tokens
142
Three-star pace
70 tpm

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

Type this snippet

Step 1 of 3 in Errors, step 7 of 27 in Language basics.

← Previous Next →