Zig NEWS

Cover image for Howto Pair Strings with Enums
David Vanderson
David Vanderson

Posted on

Howto Pair Strings with Enums

Jean-Pierre asks (https://zig.news/jpl/comment/d5) how to associate arrays with enums, so that each value of an enum is paired with an array element.

A common usecase is to have a string description paired with each enum value. Here's an example:

const std = @import("std");

pub const ErrorNames = enum {
    too_low,
    too_high,
    unknown,

    pub const ErrorNameTable = [@typeInfo(ErrorNames).Enum.fields.len][:0]const u8{
        "Too Low",
        "Too High",
        "Unknown Error",
    };

    pub fn str(self: ErrorNames) [:0]const u8 {
        return ErrorNameTable[@enumToInt(self)];
    }
};

pub fn main() !void {
    inline for (@typeInfo(ErrorNames).Enum.fields) |f| {
        std.debug.print("{d} {s} \"{s}\"\n", .{ f.value, f.name, ErrorNames.ErrorNameTable[f.value] });
    }

    var err = ErrorNames.too_low;
    std.debug.print("got enum \"{s}\"\n", .{err.str()});
}
Enter fullscreen mode Exit fullscreen mode

Outputs:

$ zig run enum_table.zig 
0 too_low "Too Low"
1 too_high "Too High"
2 unknown "Unknown Error"
got enum "Too Low"
Enter fullscreen mode Exit fullscreen mode

This also demonstrates 2 nice features of using zig's comptime:

  • easy to dump all the enum values and paired strings
  • comptime check that the string array is the same length as the enum list

Hope this helps!

Oldest comments (6)

Collapse
 
jpl profile image
Jean-Pierre

Thank you, of course it helps me, and it is very practical.

Collapse
 
jpl profile image
Jean-Pierre

Yet another request ;).
you have a complex function that returns a result...
there no problem, my problem I would like to be able to put in a "[] const u8" the name of this function... everything is in a console type interactive, there still no problem, how to do without putting in hard the name of the call to this function with a return... i'm doing this in nim-lang

the desired result: the person clicks on the area , and a table is displayed with a choice (a combo).

Maybe I'm confused, the idea is to retrieve the value and what call automatically through a function this function.

Schematically.
var callQuery= Table[string, proc(fld : var FIELD)]
proc TblCountry(fld: var FIELD) =
...
return fld

callQuery["TblCountry"] = TblCountry

program :
switch ....
val => callQuery[value) here I am getting the requested value and returning the combo choice....
I hope the google translation is clear...

To learn Zig-lang I convert my designer written under Nim-lang I advance well your subjects contributes to it.

Collapse
 
david_vanderson profile image
David Vanderson

zig.news/david_vanderson/function-...

Does this answer your question? Let me know if I misunderstood.

Collapse
 
lhp profile image
Leon Henrik Plickat

Why not just switch on the error and avoid the enum?

fn errorMessage(error: anyerror) []const u8 {
    switch(error) {
        error.MyFancyError => return "My fancy error happened",
        error.DeviceIsLitrallyOnFire => return "Check lp0",
        else => return "unexpected error",
    }
}
Enter fullscreen mode Exit fullscreen mode

Although I personally think it's better to just switch locally at the callsite of the function that may fail, like so:

mightFail() catch |err| {
    switch(err) {
        error.Whoops => log.err("something went wrong", .{}),
        else => log.err("unexpected error: {}", .{err}),
    }
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
david_vanderson profile image
David Vanderson

Yes I would normally do that too. The question asked about having an enum that was being displayed in a gui, and switching on the selected value. Lots of great ways to do it!

Collapse
 
jpl profile image
Jean-Pierre

I am progressing slowly in my study of the "Zig-lang" language, today I see why to implement the last solution.
Ps: nothing better than transcribing a software from one language to another, because we don't care about the conceptual, but about the language.