16

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
ideasman42
  • 42,413
  • 44
  • 197
  • 320
  • 1
    Note, there are some similar questions already - but they are asking about interfacing other languages *(making my initial attempts to find this information fail!)* - so asked a new question. – ideasman42 Jan 14 '17 at 09:10
  • While this is marked as a duplicate, the other question is about C++ FFI. – ideasman42 Jan 16 '17 at 15:14

1 Answers1

37

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.

ideasman42
  • 42,413
  • 44
  • 197
  • 320