Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 37 ยท Comptime and Generics

Generic Functions with comptime

Write generic functions in Zig with comptime type parameters, anytype, type inference with @TypeOf, constraints via @typeInfo and @compileError, with examples and Go generics.

Zig has no <T> syntax and no separate "generics" feature. A generic function is simply a function that takes a type as a comptime parameter. The compiler makes one specialized copy per type you use, so there is no runtime cost and no boxing.

A type as a parameter

ZIG
const std = @import("std");

fn max(comptime T: type, a: T, b: T) T {
    return if (a > b) a else b;
}

pub fn main() void {
    std.debug.print("{d}\n", .{max(i32, 3, 9)});      // 9
    std.debug.print("{d}\n", .{max(f64, 2.5, -1.0)}); // 2.5
    std.debug.print("{c}\n", .{max(u8, 'a', 'z')});   // z
}

max(i32, ...) and max(f64, ...) compile into two different functions, exactly like C++ templates but without a second language. Because T is comptime-known, the compiler also checks the body per type: a > b fails to compile for a struct type with no ordering, with an error that points at the call.

anytype: let the compiler infer

If a parameter is declared anytype, its type is taken from the argument. This is shorter and common for things like writers and formatters:

ZIG
fn double(x: anytype) @TypeOf(x) {
    return x * 2;
}

const a = double(@as(u16, 21)); // u16
const b = double(1.5);          // comptime_float

@TypeOf(x) yields the type, so you can name it in the return type. Use comptime T: type when callers should be explicit or when several parameters must share the same type; use anytype when inference reads nicer. anytype has a downside: the function signature no longer documents what is expected, so the constraint must live in the doc comment or in code (next section).

Constraining the type

Zig has no where clauses or traits. You check the type yourself with @typeInfo and report problems with @compileError:

ZIG
fn sum(comptime T: type, items: []const T) T {
    switch (@typeInfo(T)) {
        .int, .float, .comptime_int, .comptime_float => {},
        else => @compileError("sum needs a number type, got " ++ @typeName(T)),
    }
    var total: T = 0;
    for (items) |x| total += x;
    return total;
}

sum(bool, &.{true}) is rejected at compile time with your message. Because untaken branches of switch on a comptime value are not compiled, the check costs nothing at runtime.

Duck typing with method checks

You can also check for capabilities rather than kinds of types. @hasDecl(T, "name") asks whether a type has a declaration such as a method:

ZIG
fn describe(thing: anytype) void {
    const T = @TypeOf(thing);
    if (@hasDecl(T, "describe")) {
        thing.describe();
    } else {
        std.debug.print("a {s}\n", .{@typeName(T)});
    }
}

This is how the standard library accepts "anything that has a write method" without an interface type.

Comptime values, not only types

Any comptime-known value can be a parameter, which allows specialization on numbers or strings:

ZIG
fn clamp(comptime lo: i32, comptime hi: i32, x: i32) i32 {
    return @max(lo, @min(hi, x));
}
// clamp(0, 255, v) is compiled as its own function with 0 and 255 baked in

Returning types from functions

Since types are values, a function may return a type. That is how generic containers are made, and it is the subject of the next lesson. A small preview:

ZIG
fn Pair(comptime A: type, comptime B: type) type {
    return struct { first: A, second: B };
}

const IntStr = Pair(i32, []const u8);
const p: IntStr = .{ .first = 7, .second = "seven" };

Function pointers and generic callbacks

A common generic helper takes a function and applies it. Passing the function as comptime f: anytype lets the compiler inline it:

ZIG
fn apply(comptime f: anytype, x: i32) i32 {
    return f(x);
}

fn inc(x: i32) i32 { return x + 1; }
// apply(inc, 5) == 6, with the call usually inlined

For runtime choice use an explicit function-pointer type: *const fn (i32) i32.

Compared with other languages

Language Mechanism Constraint syntax
C++ templates concepts, SFINAE
Rust generics + traits where T: Trait
Go type parameters interfaces / constraints
Zig comptime T: type / anytype ordinary code + @compileError

A runnable stand-in

Go 1.18+ generics play a similar role. Go declares the constraint in the signature, where Zig would check it with @typeInfo; the idea of one source function becoming many typed versions is the same.

Go Stand-in: generic max and sum (Go generics)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Common mistakes

  • Using anytype everywhere, which hides what a function accepts. Add a short doc comment or a @compileError check.
  • Forgetting that each distinct type or comptime value produces another copy of the function, which can bloat code if abused.
  • Comparing with == on slices or strings inside generics; use std.mem.eql for those.
  • Calling a generic function with an integer literal, whose type is comptime_int; cast with @as(i32, 5) if you need a concrete type.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you write a generic function in Zig?

    Types are comptime values, so a generic function simply takes one as a comptime parameter.
  2. 2. What does @TypeOf(x) return?

    @TypeOf gives the type, so it can appear in return types or comparisons.
  3. 3. How can a generic function reject bad types?

    Constraints are ordinary comptime code ending in @compileError, so the user gets a clear build-time message.
  4. 4. How many machine-code copies does max(i32, ...) and max(f64, ...) produce?

    The function is specialized per distinct comptime argument, like a C++ template.

Summary

  • Generic functions take comptime T: type or anytype; the compiler specializes each use.
  • Constrain with @typeInfo, @hasDecl and @compileError.
  • Any comptime-known value can specialize a function, and functions can return types.
  • Be careful that anytype hides the signature and every specialization is compiled separately.

Next: Generic data structures