如何在Rust中指定枚举的底层类型? [英] How to specify the underlying type of an enum in Rust?

查看:194
本文介绍了如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆