Get non-exhaustive enum @tagName without panic?

Its there a std.meta function or something I can use to get the tagName of a non-exhaustive enum without panicking on unnamed values?

const std = @import("std");

pub fn main() !void {
    const NumEnum = enum(u8) {
        one = 1,
        _,
    };

    const two: NumEnum = @enumFromInt(2);
    const name_of_two: [:0]const u8 = @tagName(two);
    std.debug.print("{s}", .{name_of_two});
}
zig run experimental/test.zig 
experimental/test.zig:10:39: error: no field with value '@enumFromInt(2)' in enum 'test.main.NumEnum'
    const name_of_two: [:0]const u8 = @tagName(two);
                                      ^~~~~~~~~~~~~
experimental/test.zig:4:21: note: declared here
    const NumEnum = enum(u8) {zig run experimental/test.zig 
experimental/test.zig:10:39: error: no field with value '@enumFromInt(2)' in enum 'test.main.NumEnum'
    const name_of_two: [:0]const u8 = @tagName(two);
                                      ^~~~~~~~~~~~~
experimental/test.zig:4:21: note: declared here
    const NumEnum = enum(u8) {

related:

std.enums.tagName

4 Likes

Implementation using std.enums.tagName

const std = @import("std");

pub fn main() !void {
    const NumEnum = enum(u8) {
        one = 1,
        _,
    };

    const two: NumEnum = @enumFromInt(2);
    const name_of_two: []const u8 = std.enums.tagName(NumEnum, two) orelse "no name!";
    std.debug.print("{s}\n", .{name_of_two});
}

zig run experimental/test.zig 
no name!