6

Is there a way I can make a C++ style enumeration with explicit representation type in Rust? Example:

enum class Number: int16_t {
    Zero, One, Two, Three, Four, Five, Six, Seven, Eight, Nine
};

If not, is there another way I can organize variables like that? I am interfacing with an external library, so specifying the type is important. I know I could just do:

type Number = int16_t;
let One: Number = 1;
let Two: Number = 2;
let Three: Number = 3;

But that introduces a lot of redundancy, in my opinion;


Note this question is not a duplicate of Is it possible to wrap C enums in Rust? as it is about wrapping C++, not wrapping C.

Community
  • 1
  • 1
Jeroen
  • 15,257
  • 12
  • 59
  • 102
  • 1
    possible duplicate of [Is it possible to wrap C enums in Rust?](http://stackoverflow.com/questions/19433827/is-it-possible-to-wrap-c-enums-in-rust) – filmor Aug 26 '14 at 13:44
  • 1
    @fimor That question is about C style enums, which are different from C++ ones. – Jeroen Aug 26 '14 at 13:46
  • Ah, good thing you updated the question then :) – filmor Aug 26 '14 at 14:04
  • @JeroenBollen, noticed you removed "when interfacing C++" from title, is this question about interfacing C++ or not? Otherwise it looks like a duplicate of "possible to wrap C enums in Rust?" – ideasman42 Jan 15 '17 at 16:50
  • @ideasman42 I rolled back your redundant edits which did not contribute anything to the OP, however the C++ in the title can be justified. – Jeroen Jan 16 '17 at 09:57
  • This questions purpose is still a bit vague to me. Rust doesn't have C++ FFI, so assume this would be converted to a C int16_t and go via C's FFI ? https://github.com/rust-lang/rfcs/issues/602 – ideasman42 Jan 16 '17 at 12:45
  • @ideasman42 I posted this thread 2 years ago, I have no idea what my intent was at the time. – Jeroen Jan 17 '17 at 13:32

1 Answers1

16

You can specify a representation for the enum.

#[repr(i16)]
enum Foo {
    One = 1,
    Two = 2,
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
A.B.
  • 15,364
  • 3
  • 61
  • 64