Skip to content

Zig Optionals

Sometimes there’s simply no answer. You search a list and the name isn’t in it. You ask for the next line and the file has ended. A user leaves a field blank. That isn’t really an error, it’s just “nothing here”. Zig has a type for exactly this: the optional, written ?T. It’s either a value of type T or null, and like error unions, the compiler makes you check which one you’ve got before you use it.

Put ? in front of a type to make it optional. A ?u8 holds a u8, or null:

const std = @import("std");
const users = [_][]const u8{ "ada", "linus", "grace" };
fn findUser(name: []const u8) ?usize {
for (users, 0..) |user, i| {
if (std.mem.eql(u8, user, name)) return i;
}
return null;
}
pub fn main() void {
const grace = findUser("grace");
const bob = findUser("bob");
std.debug.print("grace: {?d}\n", .{grace});
std.debug.print("bob: {?d}\n", .{bob});
}

Output:

grace: 2
bob: null

findUser returns the position of the name in the list, or null if it isn’t there. Inside the function you just return i or return null, and Zig wraps the value as needed. To print an optional, add ? to the format: {?d} for a number, {?s} for a string. Plain {d} or {s} won’t compile for an optional.

An optional isn’t the value itself. It might be null, so Zig won’t let you do math with it or pass it where a plain value is expected:

const std = @import("std");
fn findAge(name: []const u8) ?u8 {
if (std.mem.eql(u8, name, "Ada")) return 36;
return null;
}
pub fn main() void {
const age = findAge("Ada");
std.debug.print("next year: {d}\n", .{age + 1});
}
main.zig:10:47: error: invalid operands to binary expression: 'optional' and 'comptime_int'
std.debug.print("next year: {d}\n", .{age + 1});
~~~~^~~

And it works the other way too: a plain type can’t hold null. const age: u8 = null; stops with “expected type ‘u8’, found ‘@TypeOf(null)’”. The rest of this lesson is about the ways to unwrap.

orelse gives you the value if there is one, or a fallback if it’s null. It’s the optional version of catch with a default:

const std = @import("std");
fn findAge(name: []const u8) ?u8 {
if (std.mem.eql(u8, name, "Ada")) return 36;
return null;
}
pub fn main() void {
const ada = findAge("Ada") orelse 0;
const bob = findAge("Bob") orelse 0;
std.debug.print("Ada: {d}, Bob: {d}\n", .{ ada, bob });
}

Output:

Ada: 36, Bob: 0

After orelse 0, ada and bob are plain u8s.

The right side of orelse doesn’t have to be a value. It can also leave: orelse return, orelse continue, orelse break. A very common one turns “missing” into an error, when missing really is a problem for this caller:

const std = @import("std");
const users = [_][]const u8{ "ada", "linus", "grace" };
fn findUser(name: []const u8) ?usize {
for (users, 0..) |user, i| {
if (std.mem.eql(u8, user, name)) return i;
}
return null;
}
fn userId(name: []const u8) !usize {
return findUser(name) orelse error.UnknownUser;
}
pub fn main() void {
std.debug.print("{!d}\n", .{userId("grace")});
std.debug.print("{!d}\n", .{userId("bob")});
}

Output:

2
error.UnknownUser

findUser says “not found” with null, because for a search that’s a normal answer. userId is used where a user must exist, so it turns null into error.UnknownUser. That’s a good habit: optionals for “might not be there”, errors for “something went wrong” (more on this choice at the end).

if (opt) |value|: check and unwrap in one step

Section titled “if (opt) |value|: check and unwrap in one step”

To run different code depending on whether the value is there, use if with a capture. Inside the first block, |age| is the plain value:

const std = @import("std");
fn findAge(name: []const u8) ?u8 {
if (std.mem.eql(u8, name, "Ada")) return 36;
if (std.mem.eql(u8, name, "Linus")) return 56;
return null;
}
pub fn main() void {
const names = [_][]const u8{ "Ada", "Bob", "Linus" };
for (names) |name| {
if (findAge(name)) |age| {
std.debug.print("{s} is {d}\n", .{ name, age });
} else {
std.debug.print("{s}: no age on file\n", .{name});
}
}
}

Output:

Ada is 36
Bob: no age on file
Linus is 56

This is the same shape as if with an error union from Zig Errors, except the else has no |err|: a null carries no extra information. Here the else is also optional. You can leave it out when there’s nothing to do for null.

|age| is a copy. If you want to change the value inside the optional, capture a pointer with |*value|:

const std = @import("std");
pub fn main() void {
var lives: ?u8 = 3;
if (lives) |*l| l.* -= 1;
std.debug.print("lives: {?d}\n", .{lives});
lives = null;
if (lives) |*l| l.* -= 1;
std.debug.print("lives: {?d}\n", .{lives});
}

Output:

lives: 2
lives: null

l is a pointer to the u8 inside lives, and l.* is the value it points at (see Zig Pointers). When lives is null, the if body is skipped, so nothing can go wrong.

You can also just compare with null: if (lives == null) or if (lives != null). That’s fine when you only need to know, not use, the value.

.? unwraps an optional and promises it isn’t null. It’s short for orelse unreachable:

const std = @import("std");
const users = [_][]const u8{ "ada", "linus", "grace" };
fn findUser(name: []const u8) ?usize {
for (users, 0..) |user, i| {
if (std.mem.eql(u8, user, name)) return i;
}
return null;
}
pub fn main() void {
const id = findUser("grace").?;
std.debug.print("grace has id {d}\n", .{id});
const other = findUser("bob").?;
std.debug.print("bob has id {d}\n", .{other});
}

You’ll see something like:

grace has id 2
thread 1837 panic: attempt to use null value
main.zig:16:34: 0x11e4e28 in main (main.zig)
const other = findUser("bob").?;
^

The first .? is fine. The second one is a broken promise, so a debug or safe build stops with a panic that points at the exact spot. In fast and small builds there’s no check, and the program carries on with nonsense (Zig Illegal Behavior explains why). Use .? only when null would be a bug in your own code, and orelse or if for anything that depends on input.

Lots of things in Zig hand out items one at a time and return null when they run out. These are called iterators, and while with a capture is how you use them:

const std = @import("std");
pub fn main() void {
var parts = std.mem.splitScalar(u8, "red,green,,blue", ',');
while (parts.next()) |part| {
std.debug.print("[{s}]", .{part});
}
std.debug.print("\n", .{});
var words = std.mem.tokenizeScalar(u8, " one two three ", ' ');
while (words.next()) |word| {
std.debug.print("[{s}]", .{word});
}
std.debug.print("\n", .{});
}

Output:

[red][green][][blue]
[one][two][three]

parts.next() returns ?[]const u8. While it gives a piece of text, the loop body runs with that piece in part. When it returns null, the loop stops. No index, no length check, no “one past the end” bugs.

The two splitters behave a little differently: splitScalar keeps the empty piece between ,,, while tokenizeScalar skips empty pieces, which is usually what you want for words separated by spaces. Zig Iterators shows how to write your own.

Pointers in Zig can’t be null, so a pointer that may point nowhere is written ?*T. The classic example is a linked list, where the last node has no next node:

const std = @import("std");
const Node = struct {
value: i32,
next: ?*Node,
};
pub fn main() void {
var third = Node{ .value = 30, .next = null };
var second = Node{ .value = 20, .next = &third };
var first = Node{ .value = 10, .next = &second };
var current: ?*Node = &first;
while (current) |node| {
std.debug.print("visit {d}\n", .{node.value});
current = node.next;
}
std.debug.print("*Node: {d} bytes, ?*Node: {d} bytes\n", .{ @sizeOf(*Node), @sizeOf(?*Node) });
}

Output:

visit 10
visit 20
visit 30
*Node: 8 bytes, ?*Node: 8 bytes

The loop walks from node to node until current becomes null. And look at the last line (from a 64-bit machine): ?*Node is the same size as *Node. Zig stores null as address zero, exactly like C does, so an optional pointer costs nothing extra. You get C’s speed with a compiler check on top. The language reference on optional pointers explains this.

Other optionals, like ?u32, need a bit of extra room to remember whether a value is there, so they’re a little bigger than the plain type.

Both say “you might not get a value”. Pick by asking whether the caller needs to know why:

Situation Use
“Not found” is a normal answer: searching a list, looking up a key ?T
The end of something: next item, next line ?T
A setting that’s allowed to be missing ?T
Something went wrong and the caller may want to know what: bad input, missing file, no memory !T

You can also combine them: !?T means “this can fail, and if it doesn’t, there may or may not be a value”. Reading lines from a file is a typical case: an I/O error is an error, the end of the file is null. You unwrap it in two steps: try for the error, then a capture for the optional, as in while (try it.next()) |item|. The language reference on optionals has more examples.

Write fn firstEven(numbers: []const i32) ?i32 that returns the first even number in the slice, or null if there isn’t one. Print the result for [_]i32{ 3, 7, 8, 10 } and [_]i32{ 1, 5 }, using orelse to print -1 when there’s none.

Hint: @rem(n, 2) == 0 checks for even numbers, including negative ones.

Show solution
const std = @import("std");
fn firstEven(numbers: []const i32) ?i32 {
for (numbers) |n| {
if (@rem(n, 2) == 0) return n;
}
return null;
}
pub fn main() void {
const a = [_]i32{ 3, 7, 8, 10 };
const b = [_]i32{ 1, 5 };
std.debug.print("{d}\n", .{firstEven(&a) orelse -1});
std.debug.print("{d}\n", .{firstEven(&b) orelse -1});
}

Output:

8
-1

&a turns the array into a slice for the function. orelse -1 unwraps the optional with a fallback, so {d} gets a plain i32.

Use std.mem.tokenizeScalar and a while loop to count the words in " the quick brown fox ". Print the count.

Hint: while (words.next()) |_| count += 1; works: |_| captures the value and throws it away.

Show solution
const std = @import("std");
pub fn main() void {
var words = std.mem.tokenizeScalar(u8, " the quick brown fox ", ' ');
var count: usize = 0;
while (words.next()) |_| count += 1;
std.debug.print("words: {d}\n", .{count});
}

Output:

words: 4

tokenizeScalar skips the extra spaces, so you get four words. With splitScalar you’d also count the empty pieces between spaces.

Write a loop that finds the smallest number in [_]u32{ 42, 7, 19 }, starting from var smallest: ?u32 = null;. Print it with {?d}.

Hint: inside the loop, use if (smallest) |s| { ... } else { ... }. The else handles the very first number.

Show solution
const std = @import("std");
pub fn main() void {
const numbers = [_]u32{ 42, 7, 19 };
var smallest: ?u32 = null;
for (numbers) |n| {
if (smallest) |s| {
if (n < s) smallest = n;
} else {
smallest = n;
}
}
std.debug.print("smallest: {?d}\n", .{smallest});
}

Output:

smallest: 7

Starting with null means “no answer yet”, which is more honest than starting with a made-up big number. If the list were empty, the program would print smallest: null.

  • ?T is a value of type T or null. Plain types can never be null.
  • You must unwrap an optional before using it. Print one with {?d} or {?s}.
  • orelse gives a default, or leaves with orelse return, orelse continue, or orelse error.X.
  • if (opt) |v| runs code only when there’s a value; |*v| lets you change it in place.
  • .? means “it’s not null, I promise”. Breaking that promise panics in debug/safe.
  • while (it.next()) |item| loops until an iterator returns null.
  • ?*T is a pointer that may be null, and it’s no bigger than a normal pointer.

Next up: Zig Error Return Traces, how to find out where an error really came from.

Quick check

1. Which of these types can hold null?
2. What is const n = find(x) orelse 0; when find returns null?
3. What happens in a debug build when you write opt.? and opt is null?
4. You want to change the number inside var count: ?u32. Which capture lets you do that?