typestar

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

  1. comptime T: type receives the element type at compile time.
  2. The body uses T like any type; each call site stamps out its own version.
  3. largest(i32, &ints) and largest(f64, &floats) are two different functions by then.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in comptime, step 17 of 27 in Language basics.

← Previous Next →

Generics in other languages