Skip to content

Latest commit

 

History

History
40 lines (31 loc) · 1.46 KB

File metadata and controls

40 lines (31 loc) · 1.46 KB

Enums

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
}

Benefits of Enums:

  • 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.

When to Use Enums:

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

Further Learning: