How to specify the underlying type of an enum in R

2019-07-18 04:09发布

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?

标签: enums rust
2条回答
疯言疯语
2楼-- · 2019-07-18 04:43

What do you mean by "We might want them"?

The A, B, and C in your program are user-defined value constructors, not a field as known in OOP. Instead, you may specify type for the parameters like shown below.

enum Message {
    Quit,
    ChangeColor(i32, i32, i32),
    Move { x: i32, y: i32 },
    Write(String),
}

The snippet comes from https://doc.rust-lang.org/book/enums.html.

查看更多
在下西门庆
3楼-- · 2019-07-18 05:06

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.

查看更多
登录 后发表回答