Hasty Briefsbeta

Bilingual

Tagged Union Subsets with Comptime in Zig

2 days ago
  • Zig supports tagged unions with compiler-enforced exhaustive switch handling, preventing bugs when new cases are added.
  • Working with a subset of a tagged union often requires a catch-all or listing all ignored cases, losing compiler safety or being verbose.
  • A real-world example: Ghostty keybind actions need to separate app-wide actions from terminal-specific actions without losing exhaustiveness.
  • Solution: Use Zig's comptime to generate a subset union type via a `ScopedAction(Scope)` function that filters fields based on a `scope()` function.
  • The `ScopedAction` function uses `@typeInfo`, `@unionInit`, and `@Type` to reify a new union type containing only scoped actions at compile time.
  • A `scoped()` method converts a full `Action` to a subset using `inline else` and comptime checks, returning null if the action is not in the target scope.
  • This approach maintains compile-time safety, self-documenting function signatures, and zero runtime cost for type generation.
  • Zig's comptime enables powerful type-level programming, balancing type safety with pragmatism.