liveBook · Manning

Generic function

As explained in Systems Programming with Zig

A generic function is a function defined with type or value parameters so it can operate across multiple concrete instantiations.

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

How Systems Programming with Zig covers it

How deep it goes
Explains type parameters and compile-time duck typing through function declarations and a worked sum, deferring custom generic data structures.
Examples
Shows a newline tokenizer, an i32 sum, and a proposed boolean sum that cannot be added.
What you can do after
Build a generic sum function from scratch using a comptime type parameter.
How it connects
Connects compile-time evaluation, duck typing, and C++ templates.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.