Zig Enums
An enum is a type whose value can be only one of a fixed list of named choices. It makes a limited set of states clear instead of hiding them in loose numbers.
Print an enum name with @tagName
The value holds the green member of Color. @tagName turns that member into its name.
const std = @import("std");
const Color = enum { red, green, blue };
pub fn main() !void {
const out = std.io.getStdOut().writer();
const c: Color = .green;
try out.print("{s}\n", .{@tagName(c)});
}
Read ordinal numbers with @intFromEnum
Red is listed first and blue is listed third. Their ordinal numbers are 0 and 2.
const std = @import("std");
const Color = enum { red, green, blue };
pub fn main() !void {
const out = std.io.getStdOut().writer();
try out.print("{d} {d}\n", .{ @intFromEnum(Color.red), @intFromEnum(Color.blue) });
}
Choose a word with a switch
A switch picks a word for the active member. The green member picks the word go.
const std = @import("std");
const Color = enum { red, green, blue };
pub fn main() !void {
const out = std.io.getStdOut().writer();
const c: Color = .green;
const word = switch (c) {
.red => "stop",
.green => "go",
.blue => "calm",
};
try out.print("{s}\n", .{word});
}
Example
const std = @import("std");
const Level = enum { low, medium, high };
pub fn main() !void {
const out = std.io.getStdOut().writer();
const l: Level = .high;
try out.print("{s} {d}\n", .{ @tagName(l), @intFromEnum(l) });
}
Key points
- Enum: An enum lists named members as the only allowed values.
- Member: Write .green to use the member named green.
- Declare: const Color = enum { red, green, blue }; defines three choices.
- Ordinal: Members are numbered from 0 in the order they are listed.
- Number: @intFromEnum converts a member to its ordinal number.
- Name: @tagName converts a member to its name as text.
In this example, Level lists low, medium, and high in that order. The value holds high, so @tagName prints high and @intFromEnum prints 2.
Note
In Zig, a switch on an enum must handle every member or add an else branch.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What is @intFromEnum(Color.blue) when Color is enum { red, green, blue }; ?