Creating enums at comptime

submited by
Style Pass
2025-01-08 10:30:06

In Basic MetaProgramming in Zig we saw how std.meta.hasFn uses @typeInfo to determine if the type is a struct, union or enum. In this post, we'll take expand that introduction and use std.builtin.Type to create our own type.

Pretend you're building a validation library which has a number of validation errors. You decide to define all of these in an enum:

You'd like users of your library to be able to define their own validation behavior including their own enum values. Ideally, you'd like to present your library enum and the app-specific enum as one cohesive type. To achieve this, we'll begin with a skeleton of our library's Validator:

The reason this is a generic is to support app-specific validators. The user's app will define their own Validator where they can add custom behavior:

To create a type at comptime the @Type builtin is used. It takes a std.builtin.Type and creates a type (this process is called reify). It's the opposite of @typeInfo. We already know that std.builtin.Type is a union and, in this case, we're interested in the enum tag. That's a std.builtin.Type.Enum, which looks like:

Leave a Comment