Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 37 ยท Comptime and Generics

Type Reflection and Comptime Tricks

Inspect types at compile time in Zig with @typeInfo, @fieldParentPtr, @field and inline for, generate code from struct fields, build lookup tables and write a tiny printer.

Because Zig can run code at compile time (see Comptime basics), it can also look at types while compiling. This is called reflection, and it is how std.fmt prints any struct, how std.json parses into any struct, and how you can write serializers and validators that work for types that do not exist yet.

@typeInfo

@typeInfo(T) returns a tagged union describing T. The tags are lowercase: .int, .float, .bool, .pointer, .array, .@"struct", .@"enum", .@"union", .optional, .error_union, and so on. Each tag carries details: bit width and signedness for ints, fields for structs, and so on.

ZIG
const std = @import("std");

const User = struct {
    id: u32,
    name: []const u8,
    admin: bool,
};

pub fn main() void {
    const info = @typeInfo(User).@"struct";
    inline for (info.fields) |field| {
        std.debug.print("{s}: {s}\n", .{ field.name, @typeName(field.type) });
    }
}
// id: u32
// name: []const u8
// admin: bool

info.fields is a comptime-known slice, and each field has name, type, a default value if any, and alignment. Looping with inline for unrolls the loop, so each iteration can handle a different field type.

@field: access by name

@field(value, "name") reads (or writes) a field whose name is a comptime string. Together with inline for it lets you write code that handles every field:

ZIG
fn describe(value: anytype) void {
    const T = @TypeOf(value);
    inline for (@typeInfo(T).@"struct".fields) |f| {
        std.debug.print("{s} = {any}\n", .{ f.name, @field(value, f.name) });
    }
}

// describe(User{ .id = 7, .name = "Ada", .admin = true });
// id = 7
// name = { 65, 100, 97 }   (because {any} prints a slice of bytes)
// admin = true

Use for strings and for numbers; prints any value in a generic debug form. To format each field according to its type, switch on @typeInfo(f.type) inside the loop.

A small "to JSON" style printer

ZIG
fn writeJson(value: anytype, w: anytype) !void {
    const T = @TypeOf(value);
    switch (@typeInfo(T)) {
        .int, .comptime_int => try w.print("{d}", .{value}),
        .bool => try w.writeAll(if (value) "true" else "false"),
        .pointer => try w.print("\"{s}\"", .{value}), // assumes []const u8
        .@"struct" => |s| {
            try w.writeAll("{");
            inline for (s.fields, 0..) |f, i| {
                if (i > 0) try w.writeAll(",");
                try w.print("\"{s}\":", .{f.name});
                try writeJson(@field(value, f.name), w);
            }
            try w.writeAll("}");
        },
        else => @compileError("unsupported type " ++ @typeName(T)),
    }
}

The recursion happens at compile time: each struct type gets its own generated printer, with no runtime type checks, no hash lookups, no vtables. An unsupported field type is a build error naming the type, not a runtime surprise.

The std.Io.Writer API changed in Zig 0.15, so the exact print and writeAll methods on the writer depend on your version. The reflection pattern stays the same.

Enums: names and values

Two helpers cover most enum needs:

ZIG
const Color = enum { red, green, blue };

const name = @tagName(Color.green);                 // "green"
const c = std.meta.stringToEnum(Color, "blue");     // ?Color = .blue
const count = @typeInfo(Color).@"enum".fields.len;  // 3

std.meta.stringToEnum returns null for an unknown name, which makes parsing config values tidy. A related tool, std.enums.EnumArray, builds an array indexed by an enum.

Generating lookup tables

A comptime block can build a table once, with the table stored directly in the binary's read-only data:

ZIG
const crc_table = blk: {
    @setEvalBranchQuota(10_000);
    var table: [256]u32 = undefined;
    for (&table, 0..) |*slot, i| {
        var c: u32 = @intCast(i);
        for (0..8) |_| {
            c = if (c & 1 != 0) (c >> 1) ^ 0xEDB88320 else c >> 1;
        }
        slot.* = c;
    }
    break :blk table;
};

This is the classic CRC-32 table. In C you would paste 256 numbers or compute them at startup. In Zig the compiler runs the loop, and crc_table costs nothing at runtime. Notice @setEvalBranchQuota, needed because the loops exceed the default budget.

Building types

Beyond reading types, @Type (and in newer releases the dedicated @Struct, @Enum, @Int builtins) can construct brand-new types from descriptions. This is how libraries make "the same struct but every field optional" or tagged unions from enums. It is advanced, rarely needed in application code, and its builtin shapes have shifted between releases, so check your version's documentation before relying on it.

A simpler tool that always works is the anonymous struct / tuple literal: .{ .a = 1, .b = "x" } has a type invented by the compiler, and std.meta.fields and @typeInfo can read it too.

Practical advice

  • Reflection is powerful, but explicit code is easier to read. Reach for it when you would otherwise repeat code per field or per type.
  • Always end with else => @compileError(...) for unsupported kinds so mistakes show up at compile time.
  • Remember compile-time cost: reflection over huge types makes builds slower.
  • The standard library helpers in std.meta (fields, fieldNames, stringToEnum, eql, Child) save you from touching @typeInfo directly in many cases.
flowchart TD
  T["type T"] --> I["@typeInfo(T)"]
  I --> K{"kind?"}
  K -->|struct| F["inline for fields"]
  K -->|enum| N["@tagName / names"]
  K -->|int, bool| P["print value"]
  F --> G["@field(value, name)"]

Caption: reflection loops over a type's description at compile time and generates specialized code.

A runnable stand-in

Go's reflect package inspects types at runtime, which is slower and less safe than Zig's compile-time version, but it shows the idea: loop over the fields of any struct and print them as JSON-ish text.

Go Stand-in: print any struct's fields (Go reflect, runtime)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Common mistakes

  • Using a plain for over info.fields and getting "unable to resolve comptime value" errors: use inline for.
  • Assuming @typeInfo tag names from older tutorials; they changed to lowercase (.int, .@"struct") in recent releases.
  • Writing the reflection function without an else => @compileError case, so unsupported types fail with confusing messages.
  • Forgetting the evaluation branch quota in big comptime loops.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does @typeInfo(T) return?

    It describes the type in detail: kind, fields, bits and so on, all known at compile time.
  2. 2. Why is inline for used to walk struct fields?

    A normal loop body has a single type for its capture; unrolling lets each field be handled with its own type.
  3. 3. What does @field(value, "name") do?

    It is field access by comptime-known name, ideal in reflection loops.
  4. 4. What is the benefit of building a CRC table in a comptime block?

    The compiler runs the loop and stores the finished table in the binary.

Summary

  • @typeInfo describes types at compile time; inline for and @field let you generate code for every field.
  • @tagName and std.meta.stringToEnum convert between enums and strings.
  • Comptime blocks can precompute tables; remember @setEvalBranchQuota.
  • Prefer explicit code unless reflection removes real repetition, and end with @compileError for unsupported kinds.

Next: Calling C from Zig