0Pricing
Learn Rust Coding · Lesson

Enums for Custom Types

Utilize enums to define types that can be one of several variants, often carrying associated data.

Enums: Custom Type Choices

Welcome to Enums for Custom Types! In Rust, enums (enumerations) let you define a type that can be one of several possible, distinct variants.

Think of an enum as a way to say, "This item can be A, OR B, OR C." It's incredibly useful for representing different states or choices.

Defining a Simple Enum

To define an enum, you use the enum keyword followed by its name and curly braces containing its variants. Each variant is a distinct choice.

Here's a simple example for cardinal directions:

enum Direction {
  North,
  South,
  East,
  West,
}

fn main() {
  let my_direction = Direction::North;
  println!("My direction is {:?}", my_direction);
}

All lessons in this course

  1. Defining and Using Structs
  2. Enums for Custom Types
  3. Powerful Pattern Matching
← Back to Learn Rust Coding