Module 3Enums & matchLesson 4 of 922 min
Enums with Data
Side and OrderType — replace stringly-typed trading code.
Enums are alternatives
rust
enum Side { Buy, Sell }
enum OrderType {
Market,
Limit(f64),
Stop { trigger: f64, limit: f64 },
}Exhaustive match
rust
enum Side { Buy, Sell }
fn label(side: Side) -> &'static str {
match side {
Side::Buy => "BUY",
Side::Sell => "SELL",
}
}
fn main() {
println!("{}", label(Side::Buy));
println!("{}", label(Side::Sell));
}Output
BUY
SELLIf you add a variant later, the compiler shows every match you forgot — pure gold for production trading code.
Stringly vs typed
| Approach | Risk |
|---|---|
side: &str |
"byu" typos |
side: Side |
typos are compile errors |
Exercise
Challenge
Add TimeInForce { Day, Gtc, Ioc } and extend describe.
Tips
- match must cover every variant
- Enums can carry data per variant
- Prefer enums over booleans for multi-state logic
Try it live
Enums with DataRust 2021
Loading editor…
Output
Press Run to compile and execute.