Determine if enum value is _

How do I determine if an enum value is _ ?

Neither of these work:

pub fn isUnknown(enum_value: anytype) bool {
    return switch (enum_value) {
        _ => true,
        else => false,
    };
}
pub fn isUnknown(enum_value: anytype) bool {
    return enum_value == ._;
}

From Non-exhaustive enum in the language reference:

A switch on a non-exhaustive enum can include a _ prong as an alternative to an else prong. With a _ prong the compiler errors if all the known tag names are not handled by the switch.

So this would work:

const Enum = enum {
    a,
    b,
    c,
    _,
};

pub fn isUnknown(enum_value: Enum) bool {
    return switch (enum_value) {
        .a, .b, .c => false,
        _ => true,
    };
}

Trying to write a generic function for this might rule out being able to use switch, though. Perhaps something in std.enums might be useful as inspiration.

EDIT: std.enums.tagName would work but you might be able to come up with something better than a linear scan across the fields (i.e. if all the named values are sequential with no gaps then you could do a >= and <= check).

3 Likes
4 Likes