Skip to content

Code that runs while compiling

14 May 2025 ยท Zig 0.14

comptime is Zig's answer to generics, macros and constant tables at once: the same language, run by the compiler. Types are values there, so a generic type is a function that returns one.

const std = @import("std");

fn Pair(comptime T: type) type {
    return struct {
        first: T,
        second: T,

        fn swapped(self: @This()) @This() {
            return .{ .first = self.second, .second = self.first };
        }
    };
}

test "a pair of anything" {
    const p = Pair(i32){ .first = 1, .second = 2 };
    try std.testing.expectEqual(@as(i32, 2), p.swapped().first);
}

A constant that takes a loop to work out is still a constant, worked out while compiling:

const squares = blk: {
    var table: [10]u32 = undefined;
    for (&table, 0..) |*s, i| s.* = @intCast(i * i);
    break :blk table;
};

test "a table built by the compiler" {
    try std.testing.expectEqual(@as(u32, 81), squares[9]);
}

And inline for unrolls a loop over what only exists while compiling, such as a struct's fields. Since 0.14 the tags of @typeInfo are lowercase, hence .@"struct":

fn fieldCount(comptime T: type) usize {
    var n: usize = 0;
    inline for (@typeInfo(T).@"struct".fields) |_| n += 1;
    return n;
}

test "count a struct's fields" {
    try std.testing.expectEqual(@as(usize, 2), fieldCount(Pair(u8)));
}