Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

enums

rust

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.

like image 523
Jeroen Avatar asked Aug 26 '14 13:08

Jeroen


People also ask

What is the default type of enum in C?

In C programming, an enumeration type (also called enum) is a data type that consists of integral constants. To define enums, the enum keyword is used. enum flag {const1, const2, ..., constN}; By default, const1 is 0, const2 is 1 and so on.

Can you cast an enum in C?

Yes. In C enum types are just int s under the covers. Typecast them to whatever you want. enums are not always ints in C.

Can we assign value to enum in C?

We can also provide the values to the enum name in any order, and the unassigned names will get the default value as the previous one plus one. The values assigned to the enum names must be integral constant, i.e., it should not be of other types such string, float, etc.

How do you initialize an enum in Rust?

Initializing Enum Variants with Values in Rustlet num = Result::Score(3.14); let bool = Result::Valid(true); Here, we are initializing the enum variants with values inside the bracket. That is, Result::Score(3.14) - initialize the Score variant with the value 3.14.


1 Answers

You can specify a representation for the enum.

#[repr(i16)]
enum Foo {
    One = 1,
    Two = 2,
}
like image 146
A.B. Avatar answered Nov 15 '22 09:11

A.B.