While implementing a function to model traversing a maze, I tried creating an enum to represent headings:
const Heading = enum {
north,
east,
south,
west,
pub fn turn_left(self: Heading) Heading {
const int_val = @intFromEnum(self);
return @typeInfo(Heading).@"enum".fields[int_val + 3 % 4];
}
pub fn turn_right(self: Heading) Heading {
const int_val = @intFromEnum(self);
return @typeInfo(Heading).@"enum".fields[int_val + 1 % 4];
}
};
However, this gave an error (pointing to the contents of the square-brackets): values of type '[]const builtin.Type.EnumField' must be comptime-known, but index value is runtime-known
I think this means that I’m not allowed to index into @"enum".fields
with a value that could vary at runtime, but only values that could be computed at compilation time. Is there a way, then, to (at runtime) find “the enum entry which is next(/previous) in the list from the current one”? This suggests that there used to be a built-in named @intToEnum
, but that doesn’t appear to exist anymore.
I suppose I could do this like so:
const Heading = enum {
north,
east,
south,
west,
pub fn turn_right(self: Heading) {
return switch(self) {
Heading.north => Heading.east,
Heading.east => Heading.south,
...
}
}
pub fn turn_left(self: Heading) {
return switch(self) {
....
}
}
}
but that feels repetitive of concepts that are already encoded in the enum itself.