Module 3Enums & matchLesson 5 of 922 min
Pattern Matching in Depth
Destructuring, match guards, and readable order-type descriptions.
Patterns cheat sheet
Limit(px)— bind inner dataStop { trigger, limit }— destructure fieldsx if x > 0.0— guard_— ignore
rust
match ot {
OrderType::Limit(px) if px > 0.0 => format!("LMT {px}"),
OrderType::Limit(_) => "invalid limit".into(),
OrderType::Market => "MKT".into(),
OrderType::Stop { trigger, limit } => format!("STP {trigger}/{limit}"),
}Nested data
Enums inside structs are normal:
rust
struct Order {
side: Side,
kind: OrderType,
}Exercise
Challenge
Match on (Side, OrderType) pairs and print combined tickets.
Tips
- Guards use if after the pattern
- Prefer explicit arms over _ in critical logic
- Destructure for clarity
Try it live
Pattern Matching in DepthRust 2021
Loading editor…
Output
Press Run to compile and execute.