rust / beginner
Snippet
Understanding Enums in Rust
Enums allow you to define a type that can be one of several variants. In this example, Direction can be North, South, East, or West. Each variant is a distinct value, and Rust ensures you handle all cases.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
enum Direction {North,South,East,West,}let heading = Direction::North;match heading {Direction::North => println!("Going north!"),Direction::South => println!("Going south!"),Direction::East => println!("Going east!"),Direction::West => println!("Going west!"),}
Breakdown
1
enum Direction {
Starts defining a new enum called Direction
2
North, South, East, West,
Four possible variants for the Direction enum
3
}
Closes the enum definition
4
let heading = Direction::North;
Creates an instance of the North variant using the :: syntax
5
match heading { ... }
Pattern matching to handle each possible variant