Achieving polymorphism via dynamic dispatch in Zig
Unlike many languages that offer interface or virtual constructs, Zig has no built-in notion of interfaces. This reflects Zig’s commitment to simplicity and performance. That doesn’t mean polymorphism is off the table. In fact Zig has the tools to build interface-like behavior, making dynamic dispatch possible.
Polymorphism in Zig: The Options
Let’s backtrack a bit. There are ways to achieve polymorphism in Zig, depending on the use case:
Generics and comptime dispatch - for static polymorphism based on types and functions.
- for static polymorphism based on types and functions. Tagged unions - for closed sets of known types, enabling sum-type polymorphism.
- for closed sets of known types, enabling sum-type polymorphism. VTable interfaces - for dynamic dispatch across heterogeneous implementations.
A common motivation for interfaces is to allow uniform typing, e.g. storing multiple implementations in an array or map. Both tagged unions and vtable-based interfaces support this.
On VTable Interfaces
In this post we’ll focus on vtable interfaces.
... continue reading