Getting Started With Rust: Enums
Enums in Rust let you define a type that can be one of several possible values.
They’re simple, useful, and something you’ll see constantly in Rust.
Creating an Enum
Let’s say a player can move in four directions:
enum Direction {
Up,
Down,
Left,
Right,
}
We can then create a direction like this:
let direction = Direction::Up;
Because direction is a Direction, Rust knows it must be one of the values we’ve defined.
Using Match
Enums are commonly used with Rust’s match statement:
fn move_player(direction: Direction) {
match direction {
Direction::Up => println!("Moving up"),
Direction::Down => println!("Moving down"),
Direction::Left => println!("Moving left"),
Direction::Right => println!("Moving right"),
}
}
Now we can call:
move_player(Direction::Right);
And get:
Moving right
One nice thing about match is that Rust makes sure you handle every possible enum value.
Enums Can Store Data
Rust enums can also contain data:
enum Action {
Move(Direction),
Attack(i32),
Wait,
}
Now an action can contain additional information:
let action = Action::Attack(25);
Here, 25 could represent the amount of damage dealt.
Why Use Enums?
Enums are great whenever something has a limited number of possible states.
For example:
enum PlayerState {
Idle,
Walking,
Attacking,
Dead,
}
This is much cleaner than using strings such as "idle" or "attacking", and Rust can prevent you from accidentally using an invalid state.
That’s really the core of enums: define the possible choices and let Rust make sure you use them correctly.
Next up, we’ll look at two extremely important enums built into Rust: Option and Result.