Zig Patterns

Zig patterns, listed here, are either consistently recurring code patterns from the Zig Standard Library (0.14.0) or lesser known language construct usage examples from the Zig Language Reference (0.14.0).

52 Likes

I’ve only looked at a few of these so far but this is awesome! My only concern is that blog posts and the like have a tendency to bit rot as the language (or standard library) evolves. If these were ultimately integrated into the standard library as “testable documentation” they could evolve along with the language and standard library.

8 Likes

I’ve updated this list to contain only Zig 0.14.0 langref/stdlib patterns, except for the Decl Literals, which aren’t in the langref (yet?), so I linked the section from latest release notes.

As always, feel free to suggest any changes.

8 Likes

I’ve just found out that you can use @field instead of std.meta.stringToEnum to get an enum literal from a string at compile-time.

In fact, there’re quite a few places in the std that use this pattern. I’ve added one of those places to the list as @enumFromString.

So, here’s how you can have the “missing” builtin @enumFromString in userland:

const std = @import("std");

fn enumFromString(comptime E: type, comptime string: [:0]const u8) E {
    if (@hasField(E, string)) {
        return @field(E, string);
    }
    @compileError("Enum " ++ @typeName(E) ++ " has no field named " ++ string);
}

pub fn main() void {
    std.debug.print("{}\n", .{enumFromString(std.zig.Ast.Mode, "zig")});
}
11 Likes