liveBook · Manning

Duck typing

As explained in Systems Programming with Zig

Duck typing is accepting a value based on whether its available operations satisfy the code's requirements rather than on an explicitly declared interface.

A generic function accepts a value when the operations in its body work with that value’s type, rather than requiring an explicitly declared interface. In Zig, a comptime type parameter enables this compile-time duck typing; functions can also check types manually. 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 sum function works with i32 values because they support addition; using bool values illustrates an operation the function cannot perform. section 4.1.3

How Systems Programming with Zig covers it

How deep it goes
Defines compile-time duck typing and demonstrates operation-based validity, while noting that functions may check types manually.
Examples
Uses a generic sum over integers and contrasts it with an attempted sum over booleans.
What you can do after
Apply it via comptime type parameters to write functions reusable across types with compatible operations.
How it connects
Connects comptime generics with C++ templates.

Also explained in

Compare how 4 books explain duck typing →

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.