Skip to content

Instantly share code, notes, and snippets.

@marler8997
Last active September 27, 2024 18:43
Show Gist options
  • Save marler8997/166726e8b8350871c6bf341df3d08e3d to your computer and use it in GitHub Desktop.
Save marler8997/166726e8b8350871c6bf341df3d08e3d to your computer and use it in GitHub Desktop.

Zig Boolean Enums

Some of my thoughts on using enums in place of bool, adding a way to opt-in to an implicit conversion could have some benefits.

Zig enums provide a convenient way to represent dual-state values (booleans) with domain-specific names. An example of this is std.builtin.Signedness:

const Signedness = enum { unsigned, signed };

It's typically queried with a switch statement like this:

switch (signedness) {
    .unsigned => {
        // ...
    },
    .signed => {
        // ...
    },
}

Using a switch provides an "exhuastiveness guarantee" that all possible values are being handled. Using an if instead results in less nesting but gives up this exhuastiveness guarantee:

if (signedness == .signed) {
    // ...
} else {
    // ...
}

A similar tradeoff exists within an expression. Using an if sacrifices the exhaustiveness guarantee in favor of fewer characters:

const foo = switch (signedness) { .unsigned => ..., .signed => ... };
const foo = if (signedness == .unsigned) ... else ...;

If there was a way to create an enum type that coerced to a bool, we could use an if statement to query these values without giving up the exhuastiveness guarantee. In addition, this would change how we'd name the type and instances. Instead of a name that encompasses both the false and true states like "signedness" we'd want a name that only represents the true state like "signed. This means we only need to create 2 names for the enum intead of 3.

const Signed = enum { unsigned, signed };

var signed = ...;

// this if statement is now guaranteed to be exhuastive
if (signed) {
} else {
}

Notes:

  • I think this would require some syntax to "opt-in", it shouldn't apply to all 2-state enums
  • I don't think we'd want bools to implicitly convert to these "enum/bool" types
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment