capypad
0 day streak
rust / beginner
Snippet

Defining and Using Enums with Data

Enums in Rust allow you to define types with a fixed set of variants. Each variant can optionally hold data — like plain constants or structs with fields. This makes enums powerful for modeling states that have different shapes. When combined with match, you can exhaustively handle every possible variant.

snippet.rs
rust
1
enum Direction {\n North,\n South,\n East,\n West,\n Move { x: i32, y: i32 },\n}\n\nfn describe(dir: Direction) -> &'static str {\n match dir {\n Direction::North => "Heading north",\n Direction::South => "Heading south",\n Direction::East => "Heading east",\n Direction::West => "Heading west",\n Direction::Move { x, y } => "Moving to",\n }\n}\n\nfn main() {\n let heading = Direction::North;\n let movement = Direction::Move { x: 10, y: 20 };\n \n println!("{} and {}", describe(heading), describe(movement));\n}
Breakdown
1
enum Direction {
Declares a new enum type named Direction
2
North, South, East, West,
Plain enum variants with no associated data
3
Move { x: i32, y: i32 },
Variant with struct-like data fields inside the enum
4
fn describe(dir: Direction) -> &'static str {
Function that takes a Direction and returns a string slice
5
Direction::Move { x, y } => "Moving to",
Pattern matching extracts bound variables from the Move variant
6
let heading = Direction::North;
Creates an instance using the :: syntax to namespace the variant