Enums in Zig
A cargo enum with its own method, exhaustively switched.
const std = @import("std");
const Cargo = enum {
general,
reefer,
hazmat,
fn stowage(self: Cargo) []const u8 {
return switch (self) {
.general => "any hold",
.reefer => "plug it in",
.hazmat => "deck only",
};
}
};
pub fn main() void {
const load: Cargo = .reefer;
std.debug.print("{s} -> {s}\n", .{ @tagName(load), load.stowage() });
}
How it works
- The enum declares three tags;
.reefernames one with the leading dot. - The method's
switch (self)must cover every tag — add one and this fails to compile. @tagNameturns the tag back into its source-code spelling.
Keywords and builtins used here
constenumfnpubreturnswitchu8void
The run, in numbers
- Lines
- 20
- Characters to type
- 339
- Tokens
- 110
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 94 seconds.
Step 2 of 3 in Structs & enums, step 14 of 27 in Language basics.