Skip to content

Zig Enums

Lots of values in a program can only be one of a few things. A traffic light is red, yellow or green. A file is open or closed. A log message is debug, info, warning or error. You could store these as strings or numbers, but then nothing stops a typo like "gren" or a mystery 7 from sneaking in. An enum is a type with a fixed list of named values, and the compiler makes sure you only ever use those names. If you know enums from C, Java or TypeScript, the basics will feel familiar. Zig’s work especially well with switch.

You write enum with a list of names, separated by commas:

const std = @import("std");
const Direction = enum {
north,
east,
south,
west,
};
pub fn main() void {
const a = Direction.north;
const b: Direction = .east;
std.debug.print("a is north: {}\n", .{a == .north});
std.debug.print("b is north: {}\n", .{b == .north});
}

Output:

a is north: true
b is north: false

The names in an enum are called its tags (or fields). There are two ways to write a value:

  • Direction.north, with the type name.
  • .east, an enum literal, when Zig already knows the type. That’s the same result-type idea as .{ ... } for structs in Zig Structs. In b == .north, Zig knows b is a Direction, so .north is too.

Tags are usually written in snake_case. Comparing with == and != works as you’d expect.

A typo is caught right away. a == .nort fails with error: no field named 'nort' in enum 'main.Direction'. With strings, that bug would only show up when the program runs, if at all.

Enums and switch belong together. Each prong handles one or more tags:

const std = @import("std");
const Light = enum { red, yellow, green };
fn advice(light: Light) []const u8 {
return switch (light) {
.red => "stop",
.yellow => "slow down",
.green => "go",
};
}
pub fn main() void {
std.debug.print("red: {s}\n", .{advice(.red)});
std.debug.print("green: {s}\n", .{advice(.green)});
}

Output:

red: stop
green: go

The best part: a switch on an enum has to handle every tag. Leave one out, and the program doesn’t build:

const std = @import("std");
const Light = enum { red, yellow, green };
pub fn main() void {
const light: Light = .red;
const text = switch (light) {
.red => "stop",
.green => "go",
};
std.debug.print("{s}\n", .{text});
}
main.zig:7:18: error: switch must handle all possibilities
const text = switch (light) {
^~~~~~
main.zig:3:27: note: unhandled enumeration value: 'yellow'
const Light = enum { red, yellow, green };
^~~~~~

This is a real help in bigger programs. When you add a new tag months later, the compiler points at every switch you need to update. An else => prong would also make the error go away, but then you lose that help, so use else only when “everything else” truly means the same thing. More on switch in Zig Switch.

To print a tag’s name, use {t} in a format string, or turn it into a string yourself with @tagName:

const std = @import("std");
const Level = enum { debug, info, warning, err };
pub fn main() void {
const level: Level = .warning;
std.debug.print("{t}\n", .{level});
std.debug.print("[{s}] disk almost full\n", .{@tagName(level)});
std.debug.print("{any}\n", .{level});
}

Output:

warning
[warning] disk almost full
.warning
  • {t} prints just the name.
  • @tagName(level) gives you the name as a string (a [:0]const u8), which you can store, compare or pass around.
  • {any} prints it the way you’d write it in code, with the dot.

error is a keyword in Zig, so it can’t be a tag name. That’s why the example uses err. (You could also write @"error", but it’s clumsy.)

Just like structs, enums can hold functions and constants. Inside a method, self is the enum value, and a switch on it is the usual way to decide what to do:

const std = @import("std");
const Direction = enum {
north,
east,
south,
west,
pub fn turnRight(self: Direction) Direction {
return switch (self) {
.north => .east,
.east => .south,
.south => .west,
.west => .north,
};
}
pub fn isVertical(self: Direction) bool {
return self == .north or self == .south;
}
};
pub fn main() void {
var facing: Direction = .north;
for (0..3) |_| {
facing = facing.turnRight();
std.debug.print("now facing {t} (vertical: {})\n", .{ facing, facing.isVertical() });
}
}

Output:

now facing east (vertical: false)
now facing south (vertical: true)
now facing west (vertical: false)

Because turnRight returns a Direction, each prong can just write .east and so on. Methods work exactly as in Zig Struct Methods: facing.turnRight() is Direction.turnRight(facing).

Each tag is stored as a small number, counting from 0 in the order you wrote them. Zig picks the smallest integer type that fits, called the tag type (or backing integer). You can choose it yourself, and give tags specific values:

const std = @import("std");
const Color = enum { red, green, blue };
const Status = enum(u16) {
ok = 200,
not_found = 404,
server_error = 500,
};
pub fn main() void {
std.debug.print("green is {d}\n", .{@backingInt(Color.green)});
std.debug.print("Color is stored as {s}\n", .{@typeName(@TypeOf(@backingInt(Color.red)))});
const s: Status = .not_found;
std.debug.print("{t} = {d}\n", .{ s, @backingInt(s) });
}

Output:

green is 1
Color is stored as u2
not_found = 404

Color has three tags, so a 2-bit u2 is enough. enum(u16) says “store this as a u16”, and = 404 sets a tag’s number. Tags without a number count up from the previous one. The language reference on enums shows a few more ways to mix them.

You’ll want an explicit tag type when the numbers mean something outside your program: HTTP status codes, values in a file format, or an enum you share with C.

@fromBackingInt goes the other way. It takes a number of exactly the tag type and gives you the enum, which it gets from the result type:

const std = @import("std");
const Status = enum(u16) {
ok = 200,
not_found = 404,
server_error = 500,
};
pub fn main() void {
const code: u16 = 500;
const s: Status = @fromBackingInt(code);
std.debug.print("{d} is {t}\n", .{ code, s });
}

Output:

500 is server_error

What if the number doesn’t match any tag? If Zig can see it while compiling, you get an error (enum 'main.Status' has no tag with value '201'). If the number only shows up while the program runs, a Debug build stops with a panic. You’ll see something like:

thread 20832 panic: invalid enum value
main.zig:12:23: 0x11e4e45 in main (main.zig)
const s: Status = @fromBackingInt(code);
^

So for numbers you don’t control (user input, a file, the network), don’t use @fromBackingInt directly. std.enums.fromInt checks first and gives you an optional: the enum, or null if the number isn’t valid:

const std = @import("std");
const Status = enum(u16) {
ok = 200,
not_found = 404,
server_error = 500,
};
pub fn main() void {
const codes = [_]u16{ 404, 201 };
for (codes) |code| {
if (std.enums.fromInt(Status, code)) |s| {
std.debug.print("{d}: {t}\n", .{ code, s });
} else {
std.debug.print("{d}: not a status I know\n", .{code});
}
}
}

Output:

404: not_found
201: not a status I know

if (x) |s| runs the first block with the value inside when there is one. Optionals get their own lesson in Zig Optionals.

Two more helpers from the standard library come up a lot. std.meta.stringToEnum turns text into a tag (or null), and std.enums.values gives you every tag in order:

const std = @import("std");
const Size = enum { small, medium, large };
pub fn main() void {
for (std.enums.values(Size)) |size| {
std.debug.print("{t} ", .{size});
}
std.debug.print("\n", .{});
const words = [_][]const u8{ "medium", "huge" };
for (words) |word| {
if (std.meta.stringToEnum(Size, word)) |size| {
std.debug.print("'{s}' is {t}\n", .{ word, size });
} else {
std.debug.print("'{s}' is not a size\n", .{word});
}
}
}

Output:

small medium large
'medium' is medium
'huge' is not a size

stringToEnum is handy for command-line options and config files: read a word, turn it into an enum once, and the rest of your program works with a type the compiler can check.

Sometimes you get numbers from outside and you know only some of them. Think of a file format where newer versions add new codes. A normal enum would panic on an unknown number. A non-exhaustive enum ends with _, which means “any other number of the tag type is allowed too”:

const std = @import("std");
const Opcode = enum(u8) {
nop = 0,
load = 1,
store = 2,
_,
};
pub fn main() void {
const bytes = [_]u8{ 1, 0, 7 };
for (bytes) |byte| {
const op: Opcode = @fromBackingInt(byte);
switch (op) {
.nop, .load, .store => std.debug.print("known: {t}\n", .{op}),
_ => std.debug.print("unknown opcode {d}\n", .{@backingInt(op)}),
}
}
}

Output:

known: load
known: nop
unknown opcode 7

Now any u8 is a valid Opcode, so @fromBackingInt never panics. The _ => prong catches the unnamed values. Unlike else, it still makes the compiler check that you’ve handled every named tag. A non-exhaustive enum needs an explicit tag type, like enum(u8). The details are in the reference under non-exhaustive enum.

Make a Light enum with red, yellow and green, and a method next that returns the light that comes after it (red to green, green to yellow, yellow to red). Starting from red, print the next four lights.

Hint: a switch on self that returns a Light, and a for (0..4) |_| loop that keeps replacing a var.

Show solution
const std = @import("std");
const Light = enum {
red,
yellow,
green,
pub fn next(self: Light) Light {
return switch (self) {
.red => .green,
.green => .yellow,
.yellow => .red,
};
}
};
pub fn main() void {
var light: Light = .red;
for (0..4) |_| {
light = light.next();
std.debug.print("{t}\n", .{light});
}
}

Output:

green
yellow
red
green

light.next() doesn’t change light; it returns a new value, which the loop stores back into the var.

Make a Day enum with the seven days of the week and a method isWeekend. Loop over every day with std.enums.values and print each one with weekend or workday.

Hint: in the switch, list .saturday, .sunday in one prong and use else for the rest. That’s a case where else is fine: every other day really is the same.

Show solution
const std = @import("std");
const Day = enum {
monday,
tuesday,
wednesday,
thursday,
friday,
saturday,
sunday,
pub fn isWeekend(self: Day) bool {
return switch (self) {
.saturday, .sunday => true,
else => false,
};
}
};
pub fn main() void {
for (std.enums.values(Day)) |day| {
const kind = if (day.isWeekend()) "weekend" else "workday";
std.debug.print("{t}: {s}\n", .{ day, kind });
}
}

Output:

monday: workday
tuesday: workday
wednesday: workday
thursday: workday
friday: workday
saturday: weekend
sunday: weekend

std.enums.values(Day) returns the tags in the order they were written, so the days come out Monday first.

Turn the words "start", "stop" and "jump" into a Command enum (with start and stop) using std.meta.stringToEnum, and print what each one does, or unknown command if it isn’t one.

Hint: stringToEnum returns an optional, so unwrap it with if (...) |cmd| { ... } else { ... }, then switch on cmd.

Show solution
const std = @import("std");
const Command = enum { start, stop };
pub fn main() void {
const words = [_][]const u8{ "start", "stop", "jump" };
for (words) |word| {
if (std.meta.stringToEnum(Command, word)) |cmd| {
switch (cmd) {
.start => std.debug.print("starting the engine\n", .{}),
.stop => std.debug.print("stopping the engine\n", .{}),
}
} else {
std.debug.print("unknown command: {s}\n", .{word});
}
}
}

Output:

starting the engine
stopping the engine
unknown command: jump

The text is checked once, at the edge of the program. After that, the switch works on a real Command, and the compiler makes sure every command is handled.

  • enum { a, b, c } makes a type whose values can only be one of those tags.
  • Write Type.tag, or just .tag when the type is known. A typo is a compile error.
  • A switch on an enum must handle every tag, so adding a tag shows you every place to update.
  • {t} and @tagName give the tag’s name; enums can have methods like structs.
  • Tags are numbers underneath: choose the type with enum(u16) and values with = 404. @backingInt and @fromBackingInt convert (new names in 0.17).
  • For numbers or text from outside, use std.enums.fromInt and std.meta.stringToEnum, which return null instead of panicking.
  • A non-exhaustive enum ends with _ and accepts every number of its tag type.

Next up: Zig Unions, for a value that can hold one of several different types.

Quick check

1. You add a new tag purple to an enum. What happens to a switch on it that has no else prong?
2. What does @backingInt(Status.not_found) give for const Status = enum(u16) { ok = 200, not_found = 404 };?
3. You read a number from a file and want an enum, without crashing on bad numbers. What do you use?
4. What does the trailing _ in enum(u8) { a, b, _ } do?