Tagged Union Subsets with Comptime in Zig – Mitchell Hashimoto

submited by
Style Pass
2024-09-24 03:00:05

Zig supports tagged unions1 and the Zig compiler will error if you switch on a tagged union without handling all possible cases. This is a great feature because it helps you avoid bugs when new cases are added to the union. Many languages support similar functionality.

However, sometimes you want to work with a subset of the tagged union. You don't want to lose compiler safety by using catch-all cases in your switch statement, but you also don't want to handle every case with a noop.

In this post, I'll illustrate a real world example of this scenario and how Zig's comptime can be used to elegantly solve it. The real world example will come from my terminal project.

The following is how keybind actions are represented in Ghostty. A keybind action is the action that a keyboard shortcut triggers. For example: ctrl+n might trigger the action to open a new window.

Most keybinding actions have no data associated with them (void) but some do. For example, the scroll_lines action has an i16 associated with it to specify the number of lines up (negative) or down (positive) to scroll.

Leave a Comment