Static Enum in Rust

Viewed 1053

Is it possible define an enum without worrying about memory allocation in Rust?

Suppose the following is the definition of my enum.

pub enum Orientation {
    North,
    South,
    East,
    West,
}

I would like to know whether it is possible to refer to the same instance of say Orientation::North in the code.

Does the following code produce two separate instances of North?

let o1 = Orientation::North;
let o2 = Orientation::North;

I know I can achieve it by defining static variables like below. Is there a better (syntactically safer/simpler/cleaner) way to do the same thing?

pub enum Orientation {
    North,
    South,
    East,
    West,
}

static NORTH: Orientation = Orientation::North;
static SOUTH: Orientation = Orientation::South;
static WEST: Orientation = Orientation::West;
static EAST: Orientation = Orientation::East;
1 Answers

The code you are asking about, at runtime, is identical to as if you had written:

let o1: u8 = 0;
let o2: u8 = 0;

Enums give you abstraction over what is really happening so you get efficiency and syntactic convenience at the same time, along with type-checking and errors when you forget a variant in a match.

Creating static "constants" won't achieve anything, because passing bytes around is about the fastest thing you could do already.

Is there a better (syntactically safer/simpler/cleaner) way to do the same thing?

The "best" way to use the enum is in exactly the simplest way possible:

let o1 = Orientation::North;
let o2 = Orientation::North;
Related