#`@tagName()` for non-exhaustive enums

1 messages · Page 1 of 1 (latest)

somber tartan
#

Is there a helper - perhaps in std.meta, std.enums, or else where - that returns an optional string? I want to be able to safely get a tag name for a non-exhaustive enum, avoiding panics which occur when the tag name isn't found and instead return null. Currently i just have a custom helper which iterates enum fields.

hollow citrus
#

none that I know of

#

there mayhaps should be

somber tartan
#

hmm. maybe i will PR one to std.meta. Any name suggestions? And this is my helper if anyone has any suggestions to improve before making a PR:

pub fn tagName(ft: FileType) ?[]const u8 {
    return inline for (std.meta.fields(FileType)) |f| {
        if (@enumToInt(ft) == f.value) break f.name;
    } else null;
}

note that std.meta.tagName() already exists: https://ziglang.org/documentation/master/std/src/std/meta.zig.html#L17

hollow citrus
#

well, I'd be wary of sending stuff to std.meta

#

andrew wants to nuke it eventually

#

to me it would make more sense to have enum related functions in std.enums

#

so maybe put it there

#

and also, just use @typeInfo(T).Enum.fields instead of std.meta.fields for the PR

#

like I said, andrew will eventually nuke that namespace

somber tartan
#

ok thanks! zeroLike. i'll post a PR link when i get around to it.

somber tartan