Multiple associated values for an enum

Hi Friends.

I’m having trouble building a data structure. I’m writing a parser, and interpreter in Zig. I want to use a value of an enum as the key for a fixed size, static, hashMap, or array of values. The enum represents tokens: Token.Type, and the data structure represents an array of parsing rules. In C this would look like this:

ParseRule rules[] = {
  [TOKEN_LEFT_PAREN]    = {grouping, call,   PREC_CALL},
  [TOKEN_RIGHT_PAREN]   = {NULL,     NULL,   PREC_NONE},
  [TOKEN_LEFT_BRACE]    = {NULL,     NULL,   PREC_NONE}, // [big]
  [TOKEN_RIGHT_BRACE]   = {NULL,     NULL,   PREC_NONE},
  // .. Truncated for brevity.
  [TOKEN_EOF]           = {NULL,     NULL,   PREC_NONE},
};

I feel like I’m almost there, but can’t seem to find a way to map this sort of structure to Zig.

Any help would be greatly appreciated.

-kow

Hi, you probably need std.EnumMap.

FYI, there’re also std.EnumSet and std.EnumArray, and even more things in std.enums namespace.

3 Likes

Awesome! This is exactly what I was looking for. Perhaps I should look through the standard library first next time.

Thanks again.

-kow

2 Likes