Card 1 / 10
Zig uses comptime parameters for generics. A generic function accepts a type at compile time:
fn max(comptime T: type, a: T, b: T) T {
return if (a > b) a else b;
}The compiler generates specialized versions for each type used. Only types that support > will compile.
T |
a |
b |
result |
|---|---|---|---|
i32 |
5 |
3 |
5 |
i32 |
-1 |
-5 |
-1 |
u8 |
200 |
100 |
200 |
f64 |
3.14 |
2.71 |
3.14 |
Use comptime T: type as the first parameter. Compare with if (a > b) a else b.
/// Return the larger of two values (works for any comparable type)
fn genericMax(comptime T: type, a: T, b: T) T {
return if (a > b) a else b;
}Card 2 / 10
Write a generic contains function that checks if a slice of any comparable type contains a target value.
fn contains(comptime T: type, items: []const T, target: T) boolThis pattern is used throughout Zig's standard library.