Lesson 4 of 9 · 26m
Comptime Without Metaprogramming Soup
Use Zig's compile-time evaluation for types, lookup tables, validation, and specialization while keeping generated behavior inspectable.
Comptime is Zig's superpower and its fastest route to unreadable code. Used well, it replaces code generation, macro systems, and runtime reflection with normal Zig that happens to run during compilation. Used badly, it creates a meta-language only the original author can debug. The rule I give teams is simple: comptime should reduce concepts, not multiply them.
Comptime is evaluation, not magic
A comptime parameter means the value must be known during compilation. Types are comptime values. This is why Zig can write generic data structures without template syntax:
fn Stack(comptime T: type) type {
return struct {
items: [128]T = undefined,
len: usize = 0,
const Self = @This();
fn push(self: *Self, value: T) !void {
if (self.len == self.items.len) return error.Full;
self.items[self.len] = value;
self.len += 1;
}
};
}
const U32Stack = Stack(u32);There is no separate template language. type is a value, functions can return types, and instantiation produces ordinary code you can inspect.
Replace tables, not judgment
Lookup tables are one of the cleanest comptime uses. Compute them once, type them precisely, and avoid runtime initialization order problems:
const byte_len = comptime blk: {
var table: [256]u8 = undefined;
for (&table, 0..) |*entry, i| {
entry.* = if (i < 0x80) 1 else if (i < 0x800) 2 else 3;
}
break :blk table;
};The advantage is not merely speed. It is determinism and clarity about when computation occurs. But if the table is easier to read written out, write it out. Compile-time cleverness is not a moral virtue.
Validate configuration before main
Comptime assertions catch impossible configurations before a binary ships:
comptime {
if (@bitSizeOf(usize) < 32) {
@compileError("this utility requires at least a 32-bit target");
}
}Use this for structural requirements: unsupported endianness, impossible feature combinations, invalid version constants, or invariants about fixed-size wire formats. Do not use it for user input validation; user input does not exist at compile time.
Comptime specialization is still an API decision
You can specialize behavior on type shape:
fn writeInt(writer: anytype, comptime T: type, value: T) !void {
switch (@typeInfo(T)) {
.int => try writer.print("{d}", .{value}),
else => @compileError("writeInt requires an integer type"),
}
}This is powerful, but anytype erases useful interface documentation. Prefer concrete types where the abstraction is not real. When you do use anytype, write tests for the supported shapes because compile errors in generic instantiations often appear far from the caller's mistake.
Inspect what the compiler sees
When comptime logic grows, make the intermediate values explicit:
const feature_count = feature_flags.len;
comptime {
if (feature_count > 16) @compileError("feature bitset overflow");
}Small named constants are easier to understand than nested inline expressions. Also remember that compile-time execution can slow builds and increase cognitive load. A millisecond saved in runtime is worthless if every future change costs ten minutes of deciphering.
Field notes
@compileErrorshould explain the violated requirement in user terms; "bad type" is not a useful diagnosis.- Comptime-generated types can produce very long error messages. Keep type constructors shallow and name intermediate types.
- A compile-time table duplicated across modules can increase binary size. Measure before calling it optimization.
- Comptime is not a sandbox escape hatch: code that must depend on runtime environment cannot be decided there.
- If a macro would have been horrible in C, the same design in Zig comptime is probably still horrible, just typed better.
- Use comptime to make illegal states unrepresentable where practical, not to show off type-level gymnastics.
Was this lesson helpful?