How to specify the underlying type of an enum in R

2019-07-18 04:51发布

问题:

This question already has an answer here:

  • How to specify the representation type for an enum in Rust to interface with C++? 1 answer

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?

回答1:

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.



回答2:

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.



标签: enums rust