Enums & Pattern MatchingAdvanced
1Question 1 of 1
rustHow do Enums with Associated Data provide expressive modeling in Rust?
Explanation & Concept
Rust enums are Algebraic Data Types (tagged unions). Unlike C-style enums that only represent integer flags, Rust enums can embed different data structures in each variant.
Code Example
rust
enum WebEvent {
PageLoad,
KeyPress(char),
Paste(String),
Click { x: i64, y: i64 },
}
fn inspect_event(event: WebEvent) {
match event {
WebEvent::PageLoad => println!("Page loaded"),
WebEvent::KeyPress(c) => println!("Key: {}", c),
WebEvent::Paste(s) => println!("Pasted: {}", s),
WebEvent::Click { x, y } => println!("Clicked at ({}, {})", x, y),
}
}How It Works & Key Takeaways
Enums with associated data allow safe, strongly-typed state modeling without complex inheritance structures.
Mock Test · 1 Questions · Optional
Ready for Slices?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions