What's the idiomatic way to write this?

What would be the idiomatic way to write an array that grows automatically (at compile time) when I add an item to an enum?

In C I do this:

typedef enum {
    A,
    B,
    C,
    FOO_COUNT,
} foo_t;

int my_array[FOO_COUNT];

This allows me to write code like this, that continues to work just fine when I add a D item before FOO_COUNT in my enum definition.

void foo_init() {
    for (int i = 0; i < FOO_COUNT; i++) {
        my_array[i] = i;
    }    
}

What's the idiomatic way to write this in Rust?I know you can literally translate this in Rust (playground), but I would hardly consider that "idiomatic".

There's no built in way to count the number of variants of an enum, but there are crates such as variant-count that can do it.

use variant_count::VariantCount;

#[derive(VariantCount)]
enum Test {
    First(i32),
    Second(Option<String>),
    Third,
}

assert_eq!(Test::VARIANT_COUNT, 3);

The Test::VARIANT_COUNT constant will be a compile-time constant, so you can use it as the length of an array.

1 Like

If you're just using the array to list the values of the enum, you could use something like strum_macros::EnumIter.

1 Like

Maybe you can model this as a match statement instead? probably less performant though.