A generic function reuses one implementation across multiple types. In Zig, a comptime type parameter lets the function work with any type for which its body is valid; the function can also check types explicitly. section 4.1.3
Listing 4.2 Comptime type parameters for fun and profit
pub fn tokenizeScalar(
comptime T: type, #1
buffer: []const T, #2
delimiter: T, #3
) TokenIterator(T, .scalar) #4
In std.mem.tokenizeScalar, the compile-time type T determines the buffer element, delimiter, and returned iterator types. Passing u8 and a newline delimiter can split a wordlist for counting. section 4.1.3
Listing 4.3 Compile-time duck typing
const std = @import("std");
fn sum(comptime T: type, values: []const T) T {
var total: T = 0;
for (values) |value| {
total += value;
}
return total;
}
pub fn main() void {
const result = sum(i32, &.{1, 2, 3});
std.debug.print("sum: {}\n", .{result});
}
The generic sum adds values of type T. It works for i32, but not for bool: the function body must be valid for the supplied type. Try swapping the call to see what the compiler says. section 4.1.3
