Enums
std.EnumSet, std.EnumMap, std.EnumArray are efficient enum-indexed collections.
const Color = enum {
red,
green,
blue,
pub fn isWarm(self: Color) bool { // enums can have methods and decls
return self == .red;
}
};
const Status = enum(u16) { // explicit tag type and values
ok = 200,
not_found = 404,
server_error = 500,
};
const Open = enum(u8) { a, b, _ }; // non-exhaustive enum (any u8 value is valid)
pub fn main() void {
const c: Color = .green; // enum literal (type inferred)
std.debug.print("{s} {d}\n", .{ @tagName(c), @intFromEnum(c) });
const s: Status = @enumFromInt(404);
std.debug.print("{}\n", .{s});
const parsed = std.meta.stringToEnum(Color, "blue") orelse .red;
_ = parsed;
switch (c) {
.red => {},
.green, .blue => {},
}
inline for (std.meta.fields(Color)) |f| std.debug.print("{s} ", .{f.name});
_ = std.enums.values(Color); // all values
}