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.
  1. detourdog

    First I had heard of duck-typing.

    https://en.wikipedia.org/wiki/Duck_typing

    After reading the page I was left with the question of isn't that dynamic inheritance? The seems like dynamic runtime.

  2. Panzerschrek

    I see little to no benefits of introducing such "traits" into a language having duck-typing in templates. It may sometimes improve code readability (slightly), but with more boilerplate code for traits handling in exchange. And the result machine code will be identical to code with no traits at all (with only duck-typing).

    C++ is a good example of this. It had duck-typing in templates for decades. Then some sort of trait-like mechanism named concepts has been introduced. The only benefit of them seems to be slightly better error messages if someone misuses a template class/function.

  3. no1guangming

    Can't load the page

More from this day

2026-10-23