rust / intermediate
Snippet
Enum with Data Variants
Rust enums can hold different types of data in each variant. Quit has no data, Move contains named fields, Write holds a String, and ChangeColor holds three u8 values. Pattern matching extracts values from variants.
snippet.rs
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
enum Message {Quit,Move { x: i32, y: i32 },Write(String),ChangeColor(u8, u8, u8),}fn process(msg: Message) {match msg {Message::Quit => println!("Quit requested"),Message::Move { x, y } => println!("Move to ({}, {})", x, y),Message::Write(text) => println!("Write: {}", text),Message::ChangeColor(r, g, b) => println!("Color: RGB({}, {}, {})", r, g, b),}}fn main() {let msgs = vec![Message::Quit,Message::Move { x: 10, y: 20 },Message::Write(String::from("Hello")),Message::ChangeColor(255, 128, 0),];for msg in msgs {process(msg);}}
Breakdown
1
enum Message {
Defines an enum with four different variants
2
Message::Move { x: i32, y: i32 }
Variant with named fields like a struct
3
Message::Write(String)
Variant holding a single String value
4
match msg {
Exhaustive pattern matching on enum variants
5
Message::Move { x, y } =>
Destructures the named fields from Move variant