Zig Generic Functions
You want one max function that works for i32, f64 and u8. In C you’d copy it three times or write a macro. Java, C# and TypeScript have <T> syntax for this, and Rust has generics with traits. Zig has no special generics syntax at all. It uses what you learned in Zig Comptime: a type is just a value that’s known at compile time, so you can pass it to a function like any other argument. This page shows the two ways to do that, comptime T: type and anytype, and how to give callers a clear error when they pass the wrong type.
A type as a parameter
Section titled “A type as a parameter”Here’s the one max for every number type:
const std = @import("std");
fn max(comptime T: type, a: T, b: T) T { return if (a > b) a else b;}
pub fn main() void { const x = max(i32, -4, 9); const y = max(f64, 2.5, 1.75); const z = max(u8, 'a', 'z'); std.debug.print("{d}\n{d}\n{c}\n", .{ x, y, z });}Output:
92.5zRead the signature from left to right: max takes a type T, then two values of that type T, and returns a T. The type has to be known while compiling (that’s what comptime says), because Zig needs it to check and build the function.
Behind the scenes, Zig makes one copy of max per type you use: one for i32, one for f64, one for u8. Each copy is as fast as if you’d written it by hand for that type. The price is a slightly bigger program when you use many types, which is rarely a problem. (Other languages call this “monomorphization”. You don’t need the word, just the idea.)
When the type doesn’t fit
Section titled “When the type doesn’t fit”What if someone calls max(bool, true, false)? You can’t ask whether true > false in Zig:
fn max(comptime T: type, a: T, b: T) T { return if (a > b) a else b;}
pub fn main() void { _ = max(bool, true, false);}main.zig:2:18: error: operator > not allowed for type 'bool' return if (a > b) a else b; ~~^~~This is compile-time duck typing. Zig doesn’t ask you to declare up front which types max accepts. It fills in T, then checks the body: if > works for that type, fine; if not, you get an error. Nothing slips through to run time.
The downside is where the error points: at a > b inside max, not at your call. In a three-line function that’s fine. In a big one, it can be hard to tell what you did wrong. Two sections down you’ll see how to give a better message.
Special cases with @typeInfo
Section titled “Special cases with @typeInfo”Inside the function, T is known at compile time, so you can ask about it and pick different code per type. @typeInfo(T) tells you what kind of type it is (an integer, a float, a struct…). You’ll explore it fully in Zig Reflection; here’s a first use.
Halving a number is a good example. For floats, x / 2 is fine. For signed integers Zig makes you choose how to round (see Zig Integers), so plain / doesn’t compile:
const std = @import("std");
fn half(comptime T: type, x: T) T { return switch (@typeInfo(T)) { .int => @divTrunc(x, 2), .float => x / 2, else => @compileError("half() needs a number type, got " ++ @typeName(T)), };}
pub fn main() void { std.debug.print("{d}\n", .{half(i32, -7)}); std.debug.print("{d}\n", .{half(u8, 9)}); std.debug.print("{d}\n", .{half(f64, -7)});}Output:
-34-3.5The switch runs at compile time, because @typeInfo(T) is known then. So the i32 copy of half only contains @divTrunc(x, 2), and the f64 copy only contains x / 2. The other prongs aren’t compiled for that type at all, which is why @divTrunc never meets a float.
The else prong turns a confusing error into a clear one. Call half(bool, true):
fn half(comptime T: type, x: T) T { return switch (@typeInfo(T)) { .int => @divTrunc(x, 2), .float => x / 2, else => @compileError("half() needs a number type, got " ++ @typeName(T)), };}
pub fn main() void { _ = half(bool, true);}main.zig:5:17: error: half() needs a number type, got bool else => @compileError("half() needs a number type, got " ++ @typeName(T)), ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++ joins two strings at compile time, and @typeName(T) gives the name of the type as text. The message now says exactly what’s wrong in words the caller understands.
anytype: let Zig work out the type
Section titled “anytype: let Zig work out the type”Writing max(i32, ...) every time gets old. With anytype, Zig takes the type from the argument instead. You saw it briefly in Zig Function Parameters:
const std = @import("std");
fn max(a: anytype, b: @TypeOf(a)) @TypeOf(a) { return if (a > b) a else b;}
pub fn main() void { const small: u8 = 3; const price: f64 = 9.99; std.debug.print("{d}\n", .{max(small, 7)}); std.debug.print("{d}\n", .{max(price, 4.5)}); std.debug.print("{d}\n", .{max(10, 20)});}Output:
79.9920a: anytype means “any type, decided at each call”. @TypeOf(a) is that type, so b: @TypeOf(a) says “b has the same type as a”, and so does the return value. When you call max(small, 7), a is a u8, and the literal 7 becomes a u8 too.
The last call is worth a second look: max(10, 20) passes two bare literals, so a is a comptime_int and the whole call runs at compile time. That’s fine for printing, but if you store the result, give it a real type: const m: u32 = max(10, 20);.
Duck typing with methods
Section titled “Duck typing with methods”anytype really shines when the “type” you care about is a behavior: “anything with a speak method”. Zig has no interfaces or traits for this. You just call the method, and Zig checks at each call that it exists:
const std = @import("std");
const Dog = struct { name: []const u8, pub fn speak(self: Dog) void { std.debug.print("{s} says woof\n", .{self.name}); }};
const Robot = struct { id: u32, pub fn speak(self: Robot) void { std.debug.print("unit {d} says beep\n", .{self.id}); }};
fn introduce(thing: anytype) void { std.debug.print("Meet a {s}: ", .{@typeName(@TypeOf(thing))}); thing.speak();}
pub fn main() void { introduce(Dog{ .name = "Rex" }); introduce(Robot{ .id = 42 });}Output:
Meet a main.Dog: Rex says woofMeet a main.Robot: unit 42 says beepDog and Robot have nothing in common except a method with the same name, and that’s enough. (The type names start with main. because the file is called main.zig: every type’s full name includes the file it lives in.) If you know Python, this is duck typing, “if it quacks like a duck…”. The difference is that Python finds out at run time, and Zig finds out while compiling.
Pass something without speak and you get:
const Cat = struct { name: []const u8,};
fn introduce(thing: anytype) void { thing.speak();}
pub fn main() void { introduce(Cat{ .name = "Tom" });}main.zig:6:10: error: no field or member function named 'speak' in 'main.Cat' thing.speak(); ~~~~~^~~~~~main.zig:1:13: note: struct declared hereconst Cat = struct { ^~~~~~That one is readable. But in a long function, with anytype passed through two or three helpers, these errors can get hard to follow. Then it’s worth checking up front.
Checking up front for a clear error
Section titled “Checking up front for a clear error”std.meta.hasMethod(T, "name") answers “does this type have a method with this name?” at compile time. Put it in front of the real work with @compileError:
const std = @import("std");
fn introduce(thing: anytype) void { const T = @TypeOf(thing); if (!std.meta.hasMethod(T, "speak")) { @compileError("introduce() needs a type with a speak() method, got " ++ @typeName(T)); } thing.speak();}
const Cat = struct { name: []const u8,};
pub fn main() void { introduce(Cat{ .name = "Tom" });}main.zig:6:9: error: introduce() needs a type with a speak() method, got main.Cat @compileError("introduce() needs a type with a speak() method, got " ++ @typeName(T)); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~The standard library does this all over the place. When you misuse a std function and get a clear sentence instead of a wall of notes, it’s usually a @compileError like this one.
Two anytypes and @TypeOf(a, b)
Section titled “Two anytypes and @TypeOf(a, b)”With two anytype parameters, the arguments can have different types. @TypeOf with several values gives you a type that fits all of them, using the same rules as an if with two different branch types (the reference calls it “peer type resolution”):
const std = @import("std");
fn add(a: anytype, b: anytype) @TypeOf(a, b) { return a + b;}
pub fn main() void { const small: u8 = 200; const big: u32 = 1000; const r = add(small, big); std.debug.print("{d} is a {s}\n", .{ r, @typeName(@TypeOf(r)) });
const f = add(@as(f32, 1.5), 2); std.debug.print("{d} is a {s}\n", .{ f, @typeName(@TypeOf(f)) });}Output:
1200 is a u323.5 is a f32A u8 and a u32 meet at u32, the bigger type, so 200 + 1000 doesn’t overflow. An f32 and a literal meet at f32.
Which one should I use?
Section titled “Which one should I use?”| Use | When |
|---|---|
comptime T: type |
Several parameters must share one type (a: T, b: T), or the type isn’t the type of any argument (like std.mem.eql(u8, a, b) or std.ArrayList(i32)). |
anytype |
Small helpers where the type obviously comes from the argument, and duck typing (“anything with a speak method”). |
Both are compile-time features with no run-time cost. When in doubt, comptime T: type is more explicit and gives clearer errors, which is why most of the standard library uses it. The language reference on compile-time parameters walks through the same max example, and the one on function parameter type inference covers anytype.
Practice
Section titled “Practice”1. Clamp
Section titled “1. Clamp”Write clamp(comptime T: type, x: T, lo: T, hi: T) T that returns lo if x is below it, hi if x is above it, and x otherwise. Test it with clamp(i32, 15, 0, 10), clamp(f64, -0.5, 0, 1) and clamp(u8, 7, 1, 9).
Hint: two ifs, or @min(@max(x, lo), hi).
Show solution
const std = @import("std");
fn clamp(comptime T: type, x: T, lo: T, hi: T) T { if (x < lo) return lo; if (x > hi) return hi; return x;}
pub fn main() void { std.debug.print("{d}\n", .{clamp(i32, 15, 0, 10)}); std.debug.print("{d}\n", .{clamp(f64, -0.5, 0, 1)}); std.debug.print("{d}\n", .{clamp(u8, 7, 1, 9)});}Output:
1007One T ties all four values together, so you can’t mix an i32 with a u8 by accident. The standard library has this too, as std.math.clamp.
2. Numbers only, please
Section titled “2. Numbers only, please”Write double(x: anytype) @TypeOf(x) that returns x * 2, but stops the build with double() only works on numbers, got <type> when x isn’t an integer or a float. Call it with a u16 and an f32.
Hint: switch on @typeInfo(@TypeOf(x)) with .int, .float => {} and an else prong. Number literals have their own kinds, .comptime_int and .comptime_float, so allow those too if you want double(5) to work.
Show solution
const std = @import("std");
fn double(x: anytype) @TypeOf(x) { const T = @TypeOf(x); switch (@typeInfo(T)) { .int, .float, .comptime_int, .comptime_float => {}, else => @compileError("double() only works on numbers, got " ++ @typeName(T)), } return x * 2;}
pub fn main() void { const a: u16 = 21; const b: f32 = 1.25; std.debug.print("{d} {d}\n", .{ double(a), double(b) });}Output:
42 2.5The switch is only there for the error message: for number types, its matching prong is empty and the function goes on to x * 2. Try double(true) to see your message.
3. Anything with an area
Section titled “3. Anything with an area”Make two structs, Square with a side: f64 and Circle with a radius: f64, each with a method area(self) f64. Then write printArea(shape: anytype) that prints area: and the result with two decimals.
Hint: inside printArea, just call shape.area(). Use std.math.pi for the circle, and {d:.2} for two decimals.
Show solution
const std = @import("std");
const Square = struct { side: f64, pub fn area(self: Square) f64 { return self.side * self.side; }};
const Circle = struct { radius: f64, pub fn area(self: Circle) f64 { return std.math.pi * self.radius * self.radius; }};
fn printArea(shape: anytype) void { std.debug.print("area: {d:.2}\n", .{shape.area()});}
pub fn main() void { printArea(Square{ .side = 3 }); printArea(Circle{ .radius = 1 });}Output:
area: 9.00area: 3.14printArea never names Square or Circle. Zig makes one copy for each, and checks in each copy that area() exists.
- Zig has no generics syntax: a generic function takes a type as a
comptimeparameter, likefn max(comptime T: type, a: T, b: T) T. - Zig makes one copy of the function per type you use, so there’s no run-time cost.
- Type checking is compile-time duck typing: Zig fills in the type and checks the body. Errors point inside the function.
switch (@typeInfo(T))picks different code per kind of type, and@compileErrorturns bad calls into clear messages.anytypetakes the type from the argument;@TypeOf(a)names it, and@TypeOf(a, b)finds a type that fits both.- For behaviors (“has a
speakmethod”), call the method on ananytype, and check withstd.meta.hasMethodfor a better error.
Next up: Zig Generic Data Structures, where a function returns a whole new type, like Stack(i32).
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Compile-Time Parameters: the official
maxexample and compile-time duck typing. - Zig language reference: Function Parameter Type Inference: how
anytypeworks. - Zig language reference: Peer Type Resolution: the rules behind
@TypeOf(a, b). - Zig language reference: Case Study: print in Zig: how
std.debug.printitself is a generic function built onanytypeandcomptime.