HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustModerate

How to get the number of elements (variants) in an enum as a constant value?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
constantenumhowvaluethenumbergetvariantselements

Problem

Is there a way to extract the number of elements in an enum?

Simple example (with imaginary number_of_elements method):

enum FooBar { A = 0, B, C, };

println!("Number of items: {}", FooBar.number_of_elements());
// "Number of items: 3"


In C I'd normally do...

enum FooBar { A = 0, B, C, };
#define FOOBAR_NUMBER_OF_ITEMS (C + 1)


However the Rust equivalent to this doesn't work:

enum FooBar { A = 0, B, C, };
const FOOBAR_NUMBER_OF_ITEMS: usize = (C as usize) + 1;

// Raises an error:
//     unimplemented constant expression: enum variants


Including the last item in the enum is very inconvenient because matching enums will error if all members aren't accounted for.

enum FooBar { A = 0, B, C, FOOBAR_NUMBER_OF_ITEMS, };


Is there a way to get the number of items in an enum as a constant value?

Note: even though this isn't directly related to the question, the reason I was wanting this feature is I'm using the builder-pattern to construct a series of actions which only make sense to run once. For this reason I can use a fixed size array the size of the enum.

Solution

Update as of 2022

There's a new function std::mem::variant_count in rust nightly version.

Example to use by rust docs.
use std::mem;

enum Void {}
enum Foo { A(&'static str), B(i32), C(i32) }

assert_eq!(mem::variant_count::(), 0);
assert_eq!(mem::variant_count::(), 3);

assert_eq!(mem::variant_count::>(), 2);
assert_eq!(mem::variant_count::>(), 2);

Context

Stack Overflow Q#41637978, score: 25

Revisions (0)

No revisions yet.