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
- Defining and Using Structs
- Enums for Custom Types
- Powerful Pattern Matching