liveBook · Manning

Generics

As explained in Systems Programming with Zig

A generic is a parameterized program construct that can be instantiated for different types or values.

Generics let one function handle values of different types. In Zig, a comptime type parameter makes the type available during compilation; the function works for a type when its body is valid for that type. This compile-time duck typing can also be supplemented with explicit type checks. 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

The declaration shows how a comptime type parameter lets tokenizeScalar accept a buffer and delimiter of that type. section 4.1.3

A sum that checks its own limits

A generic sum function accepts a comptime type and a slice of values of that type. It works for integers, but passing bool fails because booleans cannot be added. section 4.1.3

Generic code combines comptime features such as type parameters with patterns such as interfaces. Zig’s compile-time type checking is presented as a concise alternative to C-style macros and C++ templates, with errors when an operation is invalid for a supplied type. section 4.4 section 4.1.3

How Systems Programming with Zig covers it

How deep it goes
Defines comptime type parameters and duck typing, then demonstrates valid numeric input and invalid boolean input.
Examples
Uses tokenizeScalar for text splitting and a generic sum function to contrast numeric and boolean inputs.
What you can do after
Apply comptime type parameters to write functions reusable across compatible types.
How it connects
Connects generics to comptime, duck typing, interfaces, and compile-time type checking.

Also explained in

Compare how 23 books explain generics →

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.