Zig Generics
Generic code works with many types: one max function for integers and floats, one Stack for any element type. Many languages add special syntax for this (<T>, templates). Zig doesn't need any — because types are compile-time values, a generic function is just a function with a comptime T: type parameter, and a generic type is just a function that returns a type.
Generic functions
const std = @import("std");
fn largest(comptime T: type, items: []const T) T {
var best = items[0];
for (items[1..]) |x| {
if (x > best) best = x;
}
return best;
}
pub fn main() void {
const ints = [_]i32{ 4, -2, 17, 9 };
const floats = [_]f64{ 0.5, 2.25, 1.75 };
const bytes = "zig";
std.debug.print("{d}\n", .{largest(i32, &ints)});
std.debug.print("{d}\n", .{largest(f64, &floats)});
std.debug.print("{c}\n", .{largest(u8, bytes)});
}17
2.25
z
For every distinct T, the compiler generates a separate, fully optimised copy of the function. If you call it with a type that has no > (say, a struct), you get a compile error pointing at the problem.
anytype
When the type can be deduced from the argument, use anytype instead of an explicit type parameter. @TypeOf recovers the type inside:
const std = @import("std");
fn describe(value: anytype) void {
const T = @TypeOf(value);
switch (@typeInfo(T)) {
.int => std.debug.print("integer {d} ({s})\n", .{ value, @typeName(T) }),
.float => std.debug.print("float {d}\n", .{value}),
.bool => std.debug.print("bool {}\n", .{value}),
else => std.debug.print("something of type {s}\n", .{@typeName(T)}),
}
}
pub fn main() void {
describe(@as(u8, 42));
describe(@as(f32, 1.5));
describe(true);
describe("hello");
}integer 42 (u8)
float 1.5
bool true
something of type *const [5:0]u8
Because the switch on @typeInfo(T) is evaluated at compile time, only the matching branch is compiled for each call. Use anytype sparingly: an explicit comptime T: type documents what the function expects.
Generic types: functions returning types
A generic container is a function that takes a type and returns a new struct type. Inside, @This() names the struct being built:
const std = @import("std");
fn Stack(comptime T: type, comptime capacity: usize) type {
return struct {
items: [capacity]T = undefined,
len: usize = 0,
const Self = @This();
fn push(self: *Self, value: T) error{StackFull}!void {
if (self.len == capacity) return error.StackFull;
self.items[self.len] = value;
self.len += 1;
}
fn pop(self: *Self) ?T {
if (self.len == 0) return null;
self.len -= 1;
return self.items[self.len];
}
};
}
pub fn main() void {
var numbers: Stack(i32, 3) = .{};
for ([_]i32{ 1, 2, 3, 4 }) |n| {
numbers.push(n) catch |err| std.debug.print("push {d}: {t}\n", .{ n, err });
}
while (numbers.pop()) |n| std.debug.print("popped {d}\n", .{n});
var words: Stack([]const u8, 8) = .{};
words.push("first") catch unreachable;
words.push("second") catch unreachable;
std.debug.print("top word: {s}\n", .{words.pop().?});
std.debug.print("{s}\n", .{@typeName(@TypeOf(words))});
}push 4: StackFull
popped 3
popped 2
popped 1
top word: second
example.Stack([]const u8,8)
This is exactly how the standard library defines std.ArrayList(T) and std.AutoHashMap(K, V): they are functions that return types. By convention such functions use TitleCase names, since they produce types.
Calling the same type twice
Stack(i32, 3) called twice returns the same type — the compiler memoises calls with identical comptime arguments. So two variables declared as Stack(i32, 3) are fully compatible.
Constraints with comptime checks
There are no "traits" or "interfaces" in Zig's type system. Instead, you check requirements yourself at compile time and produce a clear error:
const std = @import("std");
fn sumAll(comptime T: type, values: []const T) T {
comptime {
const info = @typeInfo(T);
if (info != .int and info != .float) {
@compileError("sumAll needs a number type, not " ++ @typeName(T));
}
}
var total: T = 0;
for (values) |v| total += v;
return total;
}
pub fn main() void {
std.debug.print("{d}\n", .{sumAll(u16, &.{ 100, 200, 300 })});
std.debug.print("{d}\n", .{sumAll(f32, &.{ 0.5, 0.25 })});
}600
0.75
Another common technique is duck typing: just call the method you need (item.area()) and let the compiler complain if the type doesn't have it. @hasDecl(T, "area") and @hasField(T, "x") let you check explicitly.
Summary
| Tool | Use |
|---|---|
comptime T: type |
explicit type parameter |
anytype |
infer the type from the argument |
@TypeOf(x) |
the type of an expression |
fn Name(comptime T: type) type { return struct { … }; } |
generic type |
@This() |
the struct currently being defined |
@typeInfo, @hasDecl, @hasField |
inspect types for constraints |
Test yourself
How is a generic container like Stack(T) defined in Zig?
- With template<T> syntax
- As a function that takes
comptime T: typeand returns a type - With a macro
- With an interface
What does anytype mean for a parameter?
- The value is dynamically typed at runtime
- The type is inferred at compile time from the argument
- Any pointer
- The parameter is optional
Does Zig generate separate code for largest(i32, …) and largest(f64, …)?
- No, it uses boxing
- Yes, one specialised copy per type
- Only in Release modes
- No, generics are interpreted