beginnerCompound Types
Enum Variants
Different kinds of enum variants: unit, tuple, and struct.
Enum Variants
Different kinds of enum variants: unit, tuple, and struct.
Difficulty
Beginner
Code
rust
enum Event {
Quit,
Move { x: i32, y: i32 },
Write(String),
Color(u8, u8, u8),
}
fn describe(event: &Event) {
match event {
Event::Quit => println!("quit"),
Event::Move { x, y } => println!("move to ({}, {})", x, y),
Event::Write(text) => println!("write: {}", text),
Event::Color(r, g, b) => println!("color: #{:02x}{:02x}{:02x}", r, g, b),
}
}
fn main() {
describe(&Event::Quit);
describe(&Event::Move { x: 10, y: 20 });
describe(&Event::Write(String::from("hello")));
describe(&Event::Color(255, 128, 0));
}Explanation
Enums have unit, tuple, and struct variants.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the compound-types category to build a complete understanding of this topic.