Generics in Zig
A generic is a function that takes a type: one largest() for ints and floats.
const std = @import("std");
// A generic is just a function that takes a type at compile time.
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{ 3, 41, 12, 55 };
const floats = [_]f64{ 2.5, 8.75, 1.25 };
std.debug.print("largest int: {d}\n", .{largest(i32, &ints)});
std.debug.print("largest float: {d}\n", .{largest(f64, &floats)});
}
How it works
comptime T: typereceives the element type at compile time.- The body uses
Tlike any type; each call site stamps out its own version. largest(i32, &ints)andlargest(f64, &floats)are two different functions by then.
Keywords and builtins used here
comptimeconstf64fnfori32ifpubreturntypevarvoid
The run, in numbers
- Lines
- 17
- Characters to type
- 465
- Tokens
- 150
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 138 seconds.
Step 2 of 3 in comptime, step 17 of 27 in Language basics.