Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 37 ยท Types and Memory

Optionals

Learn Zig optionals: the ?T type, null, orelse defaults, .? unwrapping, if and while captures, optional pointers, chaining and why Zig has no null reference bugs.

"I called a function and it returned null, and then my program crashed." Billions of dollars of bugs come from that sentence. Zig's answer is simple: nothing can be null unless its type says so. A value that might be absent has an optional type, written with a question mark: ?u32, ?[]const u8, ?*Node. The compiler then forces you to handle the missing case before you can use the value.

Creating optionals

?T holds either a T or null:

ZIG
const std = @import("std");

pub fn main() void {
    var middle_name: ?[]const u8 = null;
    var age: ?u8 = 30;

    std.debug.print("{any} {any}\n", .{ middle_name, age });

    middle_name = "Grace";
    age = null;
    std.debug.print("{any} {any}\n", .{ middle_name, age });
}

A T converts to ?T automatically, so var x: ?u8 = 5; just works. The reverse never happens implicitly: you cannot add age + 1 while age is optional.

Unwrapping: four tools

1. if with a capture runs a block only when a value exists:

ZIG
if (age) |years| {
    std.debug.print("age is {d}\n", .{years});
} else {
    std.debug.print("age unknown\n", .{});
}

2. orelse supplies a default when the optional is null:

ZIG
const shown = age orelse 0;
const name = middle_name orelse "(none)";

orelse can also exit early: const v = maybe orelse return; or orelse continue, orelse break, orelse unreachable. This replaces a whole if and keeps the happy path flat.

3. .? asserts that a value is present and unwraps it:

ZIG
const years = age.?;     // panics if age is null (in safe modes)

It is shorthand for age orelse unreachable. Use it only when you have just proved the value exists, for example right after checking it, or when null would indicate a bug in your own program.

4. while with a capture loops until the optional becomes null. This is the standard iterator protocol:

ZIG
var it = std.mem.splitScalar(u8, "a,b,c", ',');
while (it.next()) |piece| {
    std.debug.print("[{s}]", .{piece});
}

Functions that return optionals

An optional return type says "might not find anything", without error codes or sentinel values like -1:

ZIG
fn findIndex(items: []const i32, target: i32) ?usize {
    for (items, 0..) |item, i| {
        if (item == target) return i;
    }
    return null;
}

pub fn main() void {
    const data = [_]i32{ 4, 8, 15, 16, 23, 42 };

    if (findIndex(&data, 15)) |i| {
        std.debug.print("found at {d}\n", .{i});
    }
    const missing = findIndex(&data, 99) orelse data.len;
    std.debug.print("not found, using {d}\n", .{missing});
}
TEXT
found at 2
not found, using 6

Many standard library functions work this way: std.mem.indexOf returns ?usize, iterators return ?T from next(), and std.meta.stringToEnum returns an optional enum.

Optional pointers

For pointers, ?*T is the same size as *T, because null uses address zero. That makes optional pointers free, and the idiomatic way to model linked structures:

ZIG
const Node = struct {
    value: i32,
    next: ?*Node = null,
};

fn length(head: ?*const Node) usize {
    var count: usize = 0;
    var current = head;
    while (current) |node| : (current = node.next) {
        count += 1;
    }
    return count;
}

The loop condition both tests and unwraps; the continue expression advances to the next node. When current becomes null, the loop ends. There is no way to dereference a null next by accident, because node.next.value will not compile until you unwrap it.

Optionals versus errors

Use an optional when absence is a normal outcome ("no match", "end of iteration"). Use an error union when something went wrong and the caller should know why ("file not found", "out of memory"). The next chapter covers errors in depth; the two combine as !?T ("may fail; if it succeeds there may still be no value").

Nested and comparing optionals

??T is an optional of an optional, rarely needed. You can compare an optional with a value directly: age == 30 is true when age holds 30, and false when it is null (no unwrapping needed). Comparing with null uses == too: if (age == null) { ... }.

Stand-ins you can run

Rust's Option is the same idea: a value that is either Some(x) or None, and cannot be used before checking.

Rust Stand-in (Rust): Option with if let, unwrap_or and iterator loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

In C the equivalent of ?*T is a plain pointer that may be NULL, and the check is entirely on you. This stand-in shows a linked list walk where the type system gives no help:

C Stand-in (C): nullable pointers and a linked list walk

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the type ?u32 mean?

    The question mark marks a value that may be absent.
  2. 2. What does value orelse 10 do?

    orelse supplies a default (or an early exit) when the optional is null.
  3. 3. What happens with maybe.? when maybe is null in a Debug build?

    The .? operator asserts presence; failing the assertion panics in safe modes.
  4. 4. Which loop form consumes an iterator until next() returns null?

    A while loop with a capture stops when the optional condition is null.
  5. 5. When should a function return an error union instead of an optional?

    Optionals mean "nothing there"; error unions carry the reason for failure.

Summary

  • ?T holds a T or null; nothing else may be null, and a T converts to ?T implicitly.
  • Unwrap with if (x) |v|, x orelse default, x.? (panics on null), or while (x) |v|.
  • orelse can return, break or continue, which keeps code flat.
  • ?*T costs no extra memory, so linked structures use it freely.
  • Optionals mean "maybe nothing"; error unions mean "something failed".

Next: Memory Layout and Alignment