Is there a way to extract the number of elements in an enumeration?
A simple example (with the imaginary number_of_elements method):
enum FooBar { A = 0, B, C, }; println!("Number of items: {}", FooBar.number_of_elements());
In C, I usually do ...
enum FooBar { A = 0, B, C, }; #define FOOBAR_NUMBER_OF_ITEMS (C + 1)
However, the Rust equivalent, equivalent to this, does not work:
enum FooBar { A = 0, B, C, }; const FOOBAR_NUMBER_OF_ITEMS: usize = (C as usize) + 1;
Including the last element in an enumeration is very inconvenient, because matching enumerations will be an error if all members are not taken into account.
enum FooBar { A = 0, B, C, FOOBAR_NUMBER_OF_ITEMS, };
Is there a way to get the number of elements in an enumeration as a constant value?
Note: although this is not directly related to the question, the reason I wanted this function is to use the builder-pattern to build a series of actions that only make sense to run once. For this reason, I can use an array of a fixed size enumeration size.
enums rust
ideasman42
source share