Zig Has No Traits, So This Developer Built Them in Userland

We have traits at home

Zig Has No Traits, So This Developer Built Them in Userland

Zig offers two paths to polymorphism: runtime interfaces with vtables and dynamic dispatch, or comptime duck typing with monomorphization. The first gives type contracts but blocks compiler optimization; the second is fast but loosely specified. Axel Magnus proposes a third convention: Traits as comptime structs holding related functions over a type, inspired by OCaml. Passing a trait struct into a function gives a clear contract, keeps LSP autocompletion working, and lets the compiler inline and unroll loops with no library machinery required.

Traits are just bags of functions and types that tell the receiving function how to execute subtasks that it's not responsible for defining. They behave a lot like vtables, except that they are evaluated at comptime rather than runtime.

More from this day

2026-10-23