An enum defines a user-defined type that can be one of several possible variants. Each variant can have its own associated data or be unit-like (containing no data). Enums provide a clear way to express different states or possibilities within your data.
enum Direction {
North,
East,
South,
West,
}
fn main() {
let my_direction = Direction::North;
let new_direction = my_direction; // No error, because Direction is Copy
move_around(new_direction);
}
fn move_around(direction: Direction) {
// implements logic to move a character around
}- Type Safety: Enums enforce data integrity by restricting values to the defined variants, preventing unexpected types.
- Readability: Enums make code more readable by clearly expressing different states or possibilities within your data.
- Pattern Matching: The match expression provides a powerful way to handle different enum variants concisely.
- Flexibility: Enums can accommodate various data types within variants, offering versatility in data representation.
Consider using enums when you have a set of finite, related possibilities for your data. They are ideal for representing:
- States in a program
- Choices or options
- Error types
- The Rust Programming Language Book: https://doc.rust-lang.org/book/
- Rust by Example: https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html