如何在Rust中指定枚举的底层类型? [英] How to specify the underlying type of an enum in Rust?
问题描述
u8
的数组中的功能。 enum MyEnum {
A = 0,
B,
C,
}
可以使用 u8
数组并将其与一些常量进行比较,但我希望有利于使用枚举确保在匹配语句中处理所有可能性。
如何指定它,以便它的 size_of
匹配所需的整数类型?
可以使用表示( repr
)说明符。
#[repr(u8)]
枚举MyEnum {A = 0,B,C,}
在类型范围之外的分配值将引发编译器警告。
Given a simple enum with a few un-typed values, it might be desirable that the size of this enum use a smaller integral type then the default. For example, this provides the ability to store the enum in an array of u8
.
enum MyEnum {
A = 0,
B,
C,
}
It's possible to use a u8
array and compare them against some constants, but I would like to have the benefit of using enums to ensure all possibilities are handled in a match statement.
How can this be specified so its size_of
matches the desired integer type?
This can be done using the representation (repr
) specifier.
#[repr(u8)]
enum MyEnum { A = 0, B, C, }
Assigned values outside the range of the type will raise a compiler warning.
这篇关于如何在Rust中指定枚举的底层类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!