Enums

The enum keyword allows the creation of a type which has a few different variants:

  1. fn generate_random_number() -> i32 {
  2. 4 // Chosen by fair dice roll. Guaranteed to be random.
  3. }
  4. #[derive(Debug)]
  5. enum CoinFlip {
  6. Heads,
  7. Tails,
  8. }
  9. fn flip_coin() -> CoinFlip {
  10. let random_number = generate_random_number();
  11. if random_number % 2 == 0 {
  12. return CoinFlip::Heads;
  13. } else {
  14. return CoinFlip::Tails;
  15. }
  16. }
  17. fn main() {
  18. println!("You got: {:?}", flip_coin());
  19. }

Key Points:

  • Enumerations allow you to collect a set of values under one type
  • This page offers an enum type CoinFlip with two variants Heads and Tail. You might note the namespace when using variants.
  • This might be a good time to compare Structs and Enums:
    • In both, you can have a simple version without fields (unit struct) or one with different types of fields (variant payloads).
    • In both, associated functions are defined within an impl block.
    • You could even implement the different variants of an enum with separate structs but then they wouldn’t be the same type as they would if they were all defined in an enum.