liveBook · Manning

Comptime type parameter

As explained in Systems Programming with Zig

A comptime type parameter is a Zig function parameter whose type value is supplied and evaluated at compile time.

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

How Systems Programming with Zig covers it

How deep it goes
Explains a generic function declaration and compile-time duck typing through arithmetic, while deferring custom data structures and generic behavior.
Examples
Uses a newline-delimited wordlist tokenizer and a generic sum with integer and boolean inputs.
What you can do after
Apply it using Zig’s std.mem.tokenizeScalar and a generic sum function.
How it connects
Connects generic functions with compile-time duck typing and explicit type checks.

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.