liveBook · Manning

Error union

As explained in Systems Programming with Zig

An error union is a Zig type whose values contain either an error or a payload value of an inner type.

An error union holds either an error or a payload value of an inner type. Zig writes the type with `!`, such as `FibonacciError!i32`. A function can name its error set explicitly or let the compiler infer it. section 3.2.2

Errors are values defined by error sets. In the checked Fibonacci function, an input above the limit returns an error; otherwise, the function returns a number. Calls use `try`, `catch`, or an `if` capture to handle the result. section 3.2.2

Listing 3.2 Fibonacci but checked
const FibonacciError = error { OverFibonacciLimit };

const fibonacci_limit = 30;

fn fibonacci(n: usize) FibonacciError!i32 { #1
    if (n == 0) {
        return 0;
    } else if (n == 1) {
        return 1;
    } else if (n > fibonacci_limit) {
        return error.OverFibonacciLimit; #2
    }
    return try fibonacci(n - 1) + try fibonacci(n - 2); #3
}

The checked Fibonacci function shows an error-union return type, an explicit error set, and a recursive call using `try`. section 3.2.2

Choose how to handle the result:

  • Capture success or failure with an `if` expression. section 3.2.2
  • Use `catch` to handle an error locally or return it. section 3.2.2
  • Use `try` when the call appears inside code that can return the error. section 3.2.2

How Systems Programming with Zig covers it

How deep it goes
Defines error unions and demonstrates explicit or inferred error sets, Fibonacci validation, and result handling with `if`, `catch`, and `try`.
Examples
Demonstrates a checked Fibonacci function that rejects inputs above a limit and shows several ways to handle its result.
What it assumes
Teaches error sets before error unions, so the treatment builds the necessary error-type context rather than assuming it.
What you can do after
Apply Zig's `if`, `catch`, and `try` syntax to handle error-union results.
How it connects
Connects error unions to error sets and to `try` and `catch` expressions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.