Tech News
← Back to articles

Partially Matching Zig Enums

read original related products more articles

Partially Matching Zig Enums

A short post about a neat little Zig idiom. Consider your average {sum type, variant, tagged union, enum, alt}:

enum U { A ( i32 ), B ( i32 ), C, }

Usually, you handle it like this:

match u { U:: A (_) => handle_a (), U:: B (_) => handle_b (), U::C => handle_c (), }

But once in a while, there’s common handling code you want to run for several variants. The most straightforward way is to duplicate:

match u { U:: A (_) => { handle_ab (); handle_a (); } U:: B (_) => { handle_ab (); handle_b (); } U::C => handle_c (), }

But this gets awkward if common parts are not easily extractable into function. The “proper” way to do this is to refactor the enum:

enum U { AB (AB), C } enum AB { A ( i32 ), B ( i32 ), }

This gets very awkward if there’s one hundred usages of U , 95 of them look better with flat structure, one needs common code for ab case, and the four remaining need common code for ac.

... continue reading