A comptime type parameter lets a Zig function reuse the same code with multiple types. The caller supplies the type at compile time; the function can then use it in other parameter and return types. 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, comptime T: type supplies the element type for the buffer, delimiter, and returned iterator. Passing u8 lets the function tokenize a byte wordlist on newline characters. section 4.1.3
The function body is duck typed: it must be valid for the supplied type. A function can also check types explicitly. There is no promise that every type will work. 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});
}
This generic sum uses T for both the input elements and result. sum(i32, &.{1, 2, 3}) produces 6; try bool instead and the addition is invalid. section 4.1.3
