TExcelTAD
Home › Zig › Zig Optionals

Zig Optionals

Sometimes a value may simply be absent: a search finds nothing, a configuration key is missing, a linked list has no next node. Zig expresses this with optional types, written with a question mark: ?T is "either a T or null". Only optional types can be null, so the dreaded null-pointer crash of C and Java cannot sneak into ordinary values.

Declaring optionals

zig · try it yourself
const std = @import("std");

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

    std.debug.print("middle: {?s}, age: {?d}\n", .{ middle_name, age });
    middle_name = "Van";
    std.debug.print("middle: {?s}\n", .{middle_name});
    std.debug.print("is null? {}\n", .{age == null});
}
middle: null, age: 29
middle: Van
is null? false

The ? in {?s} and {?d} tells the formatter the value is optional.

You must unwrap before use

A ?u8 is not a u8. Doing arithmetic with it directly does not compile — the compiler forces you to handle the null case first. There are four ways to unwrap:

Syntax When the value is null
if (opt) |v| { … } else { … } runs the else branch
opt orelse default uses default
opt orelse return / orelse break / orelse continue leaves the function / loop
opt.? panics (in safe builds) — use only when null is impossible

if with capture

zig · try it yourself
const std = @import("std");

fn findUser(id: u32) ?[]const u8 {
    return switch (id) {
        1 => "admin",
        2 => "guest",
        else => null,
    };
}

pub fn main() void {
    const ids = [_]u32{ 2, 7 };
    for (ids) |id| {
        if (findUser(id)) |name| {
            std.debug.print("user {d} is {s}\n", .{ id, name });
        } else {
            std.debug.print("user {d} does not exist\n", .{id});
        }
    }
}
user 2 is guest
user 7 does not exist

orelse

orelse supplies a fallback — perfect for defaults:

zig · try it yourself
const std = @import("std");

fn lookupPort(service: []const u8) ?u16 {
    if (std.mem.eql(u8, service, "http")) return 80;
    if (std.mem.eql(u8, service, "https")) return 443;
    return null;
}

pub fn main() void {
    const services = [_][]const u8{ "https", "gopher", "http" };
    for (services) |s| {
        const port = lookupPort(s) orelse 8080;
        std.debug.print("{s:<7} -> {d}\n", .{ s, port });
    }

    const scores = [_]?u32{ 10, null, 7, null, 3 };
    var sum: u32 = 0;
    for (scores) |maybe| {
        const s = maybe orelse continue; // skip missing scores
        sum += s;
    }
    std.debug.print("sum of present scores: {d}\n", .{sum});
}
https   -> 443
gopher  -> 8080
http    -> 80
sum of present scores: 20

The .? shortcut

opt.? is short for opt orelse unreachable. It is fine when you have just checked, or when null would be a programming error, but it crashes a safe build if you are wrong:

zig
const first_space = std.mem.indexOfScalar(u8, "hello world", ' ').?; // 5

Optional pointers

For pointers, the optional costs nothing: ?*T uses the address 0 to mean null, exactly like a C pointer — but the type system still makes you check it. That is how linked structures are built:

zig · try it yourself
const std = @import("std");

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

pub fn main() void {
    const third = Node{ .value = 30, .next = null };
    const second = Node{ .value = 20, .next = &third };
    const first = Node{ .value = 10, .next = &second };

    var current: ?*const Node = &first;
    while (current) |node| : (current = node.next) {
        std.debug.print("{d} ", .{node.value});
    }
    std.debug.print("\n", .{});
    std.debug.print("?*Node is {d} bytes, *Node is {d} bytes\n", .{ @sizeOf(?*const Node), @sizeOf(*const Node) });
}
10 20 30 
?*Node is 8 bytes, *Node is 8 bytes

Optionals vs errors

Use When
?T absence is normal and needs no explanation ("not found")
E!T something failed and the caller may want to know why

You can even combine them: !?T means "an error, or a value that may be absent" — for example, reading the next line from a file can fail, or there may be no more lines.

Test yourself

Which type can hold null?

  1. u32
  2. *u32
  3. ?u32
  4. []u32

What is (@as(?u8, null) orelse 5)?

  1. null
  2. 0
  3. 5
  4. A compile error

What does x.? do when x is null in a Debug build?

  1. Returns 0
  2. Returns null
  3. Panics
  4. Skips the statement