capypad
0 day streak
rust / beginner
Snippet

Defining and Using Enums

Enums allow you to define a type by enumerating its possible variants. In this example, Direction has four variants representing cardinal directions. You can use match expressions to handle each variant. Enums are useful for representing a fixed set of related choices.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
enum Direction {
North,
South,
East,
West,
}
 
fn get_opposite(dir: Direction) -> Direction {
match dir {
Direction::North => Direction::South,
Direction::South => Direction::North,
Direction::East => Direction::West,
Direction::West => Direction::East,
}
}
 
fn main() {
let heading = Direction::North;
println!("Heading: {:?}", heading);
let opposite = get_opposite(heading);
println!("Opposite: {:?}", opposite);
}
Breakdown
1
enum Direction { ... }
Defines an enum with four variants representing directions
2
Direction::North => Direction::South
Pattern matches each variant and returns the opposite direction
3
let heading = Direction::North;
Creates an instance of the enum variant