How to loop over enums

I have an enum called Key

pub const Key = enum {
    Right,
    Left,
    Up,
    Down,
    A,
    B,
    Select,
    Start,
};

And I want to test my controller code to make sure the release function works. To do this I want to loop over every key and set it to pressed, then set one key to released and assert the value. When trying to loop over the enum I keep getting this error:

error: values of type '[ ]const builtin.Type.EnumField' must be comptime-known, but index value is runtime-known
    for (keys) |k| {

This is my test code.

fn release_and_assert(key: Key, register: usize, expected: u8) !void {
    var interrupt = Interrupt.Interrupt.init();
    var keypad = KeyPad.init(&interrupt);
    const info = @typeInfo(Key);
    const keys = info.@"enum".fields;
    for (keys) |k| {
        keypad.press(k);
    }
    keypad.release(key);
    try std.testing.expect(keypad.register[register] == expected);
}

You want to use std.enums.values.

2 Likes

Thank you. Is this a recent change? I tried searching online but only found the typeInfo I was using or std.meta

nope, the type info is type metadata information, in particular info.@"enum".fields is a list of the type std.builtin.Type.EnumField, which contains a comptime_int that is the integer value of the field, and is a comptime only type hence your error.

If you look at the source of std.enums.values you can see it creates a list of values from the list of EnumField.