如何获取枚举中元素(变量)的数量作为常数? [英] How to get the number of elements (variants) in an enum as a constant value?
问题描述
是否可以提取枚举中元素的数量?
Is there a way to extract the number of elements in an enum?
简单示例(虚构的 number_of_elements
方法):
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"
在C中,我通常会这样做。 ..
In C I'd normally do...
enum FooBar { A = 0, B, C, };
#define FOOBAR_NUMBER_OF_ITEMS (C + 1)
但是Rust等效于此工作:
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?
注意:即使这与问题没有直接关系,我想要此功能的原因是我正在使用 builder-pattern 来构造一系列仅一次运行很有意义。因此,我可以使用枚举大小的固定大小的数组。
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.
推荐答案
您可以使用程序化宏:
extern crate proc_macro;
extern crate syn;
#[macro_use]
extern crate quote;
use proc_macro::TokenStream;
#[proc_macro_derive(EnumVariantCount)]
pub fn derive_enum_variant_count(input: TokenStream) -> TokenStream {
let syn_item: syn::DeriveInput = syn::parse(input).unwrap();
let len = match syn_item.data {
syn::Data::Enum(enum_item) => enum_item.variants.len(),
_ => panic!("EnumVariantCount only works on Enums"),
};
let expanded = quote! {
const LENGTH: usize = #len;
};
expanded.into()
}
读者,以确保可以在同一模块中多次使用此派生宏。
It is left as an excercise to the reader to ensure that this derive macro can be used multiple times within the same module.
要使用该宏,只需附加#[derive( EnumVariantCount)]
到您的枚举。现在应该有一个名为 LENGTH
的全局常量。
To use the macro, just attach #[derive(EnumVariantCount)]
to your enum. There should now be a global constant named LENGTH
.
这篇关于如何获取枚举中元素(变量)的数量作为常数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!