capypad
0 day streak
rust / beginner
Snippet

Basic Enum Definition

Enums define types with fixed variants. Variants can be unit-like, tuple-like (with data), or struct-like. The 'match' expression exhaustively handles all enum variants. 'if let' provides a concise way to match single patterns.

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
23
24
25
26
27
28
enum Direction {
North,
South,
East,
West,
}
 
enum Status {
Active(u32),
Inactive,
Suspended { reason: String },
}
 
fn main() {
let heading = Direction::North;
match heading {
Direction::North => println!("Heading north"),
Direction::South => println!("Heading south"),
Direction::East => println!("Heading east"),
Direction::West => println!("Heading west"),
}
let current = Status::Active(42);
if let Status::Active(credits) = current {
println!("Active with {} credits", credits);
}
}
Breakdown
1
enum Direction { North, South, East, West }
Simple enum with unit variants
2
enum Status { Active(u32), Inactive, Suspended { reason: String } }
Enum with tuple and struct variants
3
Direction::North
Access variant using :: path separator
4
if let Status::Active(credits) = current
Pattern match single variant without exhaustiveness