hn.today

We have traits at home

axelmagn.com17 points4 comments
Screenshot of We have traits at home

This describes a practical convention for expressing compile-time type contracts in Zig by treating traits as plain comptime structs that bundle related functions and types for a given type. It contrasts this approach with Zig's two common polymorphism patterns - runtime interfaces using opaque pointers and vtables, and comptime duck typing via anytype/monomorphisation - arguing that traits sit between them: explicit and checked at compile time like duck typing, but organized and discoverable like interfaces without incurring runtime dispatch overhead. The piece demonstrates how traits let you pass behavior (e.g., arithmetic ops) into generic functions as a single object rather than many separate comptime parameters, and shows how this yields clear contracts, good IDE support, and compiler-friendly inlining.

Substantive examples include a Reducer trait for folding, a Num trait for arithmetic, and a mobius function that consumes a Num trait; patterns for implementing traits on user and primitive types (e.g., builtinNum) are shown. It also sketches utility helpers (impl, getTrait), trait functors, and lists useful trait patterns (Into/From, Index, Iterator), and closes with practical cautions and encouragement for adopting trait-based abstractions in Zig userland.

Read on axelmagn.com4 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.