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

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::<Void>(), 0);
assert_eq!(mem::variant_count::<Foo>(), 3);

assert_eq!(mem::variant_count::<Option<!>>(), 2);
assert_eq!(mem::variant_count::<Result<!, !>>(), 2);

Leave a Comment

tech