Zig Interface Revisited

https://news.ycombinator.com/rss Hits: 15
Summary

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. Tagged unions - 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. While I was doing the ZigJR project, I had the need for using interfaces to plug in different implementations. There had been a number of approaches developed over time to make vtable interface possible in Zig. After a deep dive into the language, I have settled on one pattern. With some finetuning, this pattern provides a clean, flexible, and reusable approach, with little to no impact on implementation types. Goals of This Interface Pattern This approach achieves: Clear separation between interface and implementation. No changes required in implementation types. Full dynamic dispatch via function pointers. Uniform type for all interface instances (enabling storage in arrays, maps, etc.). Let’s explore how it works step-by-step. Example Use Case: Loggers Let’s say we’re building a logging system that supports multiple backends: A debug logger that prints to the console. A file logger that writes to disk. And others. Each logger supports a common interface: log() and setLevel(). Note: The code b...

First seen: 2025-07-19 16:29

Last seen: 2025-07-20 06:31