如何在 Rust 中创建具有常量值的枚举? [英] How can I create enums with constant values in Rust?
问题描述
我可以这样做:
enum MyEnum {
A(i32),
B(i32),
}
但不是这个:
enum MyEnum {
A(123), // 123 is a constant
B(456), // 456 is a constant
}
我可以使用单个字段为 A
和 B
创建结构,然后实现该字段,但我认为可能有更简单的方法.有吗?
I can create the structures for A
and B
with a single field and then implement that field, but I think there might be an easier way. Is there any?
推荐答案
回答这个问题的最好方法是弄清楚为什么要在枚举中使用常量:您是将值与每个变体相关联,还是希望每个变体都是那个值(就像 C 或 C++ 中的 enum
一样)?
The best way to answer this is working out why you want constants in an enum: are you associating a value with each variant, or do you want each variant to be that value (like an enum
in C or C++)?
对于第一种情况,让枚举变体不带数据并创建一个函数可能更有意义:
For the first case, it probably makes more sense to just leave the enum variants with no data, and make a function:
enum MyEnum {
A,
B,
}
impl MyEnum {
fn value(&self) -> i32 {
match *self {
MyEnum::A => 123,
MyEnum::B => 456,
}
}
}
// call like some_myenum_value.value()
这种方法可以多次应用,将许多单独的信息与每个变体相关联,例如也许你想要一个 .name() ->&'static str
方法也是如此.将来,这些函数甚至可以标记为const
函数.
This approach can be applied many times, to associate many separate pieces of information with each variant, e.g. maybe you want a .name() -> &'static str
method too. In the future, these functions can even be marked as const
functions.
对于第二种情况,您可以指定显式整数标记值,就像 C/C++ 一样:
For the second case, you can assign explicit integer tag values, just like C/C++:
enum MyEnum {
A = 123,
B = 456,
}
这可以以所有相同的方式match
,但也可以转换为整数MyEnum::A as i32
.(请注意,像 MyEnum::A | MyEnum::B
这样的计算在 Rust 中并不自动合法:枚举具有特定值,它们不是位标志.)
This can be match
ed on in all the same ways, but can also be cast to an integer MyEnum::A as i32
. (Note that computations like MyEnum::A | MyEnum::B
are not automatically legal in Rust: enums have specific values, they're not bit-flags.)
这篇关于如何在 Rust 中创建具有常量值的枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!