Enums and Matching Pattern

  • Enums:

    • Enums (short for "enumerations") are types that allow you to define a value that can be one of several variants.

    • Multiple variants types in single enum:

      enum Message {
        Quit,                       // No data
        Move { x: i32, y: i32 },    // Named fields
        Write(String),              // Single unnamed field
        ChangeColor(u8, u8, u8),    // Multiple unnamed fields
      }
  • Matching Pattern:

    • Matching pattern syntax allows you to compare a value against a series of patterns and execute code based on the matching pattern.

    • You can destructure complex data types like structs, enums, and tuples in a match.

    • You can add conditions to patterns using if guards.

enums1.rs

  • In this exercise we need to define types of messages as used in the main function.

  • So we simply add all of the types available in the main function into enum definition.

enums2.rs

  • We can have multiple variants types in single enum.

  • In this task we need to write 5 variants.

enums3.rs

  • In this exercise we need to create matching pattern syntax for all the available variants in Message enum and call it's respective method.

  • For each variants that have data, we want to catch or get that data so we can use it as arguments when calling it's respective method.

  • This pattern syntax will bind data in the message enum variants into the defined variables.

Last updated