Structs, enums and pattern matching
Pattern matching
match does more than compare values: it destructures. Each arm can pull a variant's data into variables and use them right away.
enum Order { Market { quantity: f64 }, Limit { quantity: f64, price: f64 }, Cancel(u64),} fn describe(order: &Order) -> String { match order { Order::Market { quantity } => format!("achat de {quantity} au marché"), Order::Limit { quantity, price } if *price > 1_000.0 => { format!("limite élevée : {quantity} à {price}") } Order::Limit { quantity, price } => format!("{quantity} à {price}"), Order::Cancel(id) => format!("annulation de l'ordre {id}"), }} fn main() { println!("{}", describe(&Order::Limit { quantity: 10.0, price: 1_500.0 })); println!("{}", describe(&Order::Cancel(7)));}if *price > 1_000.0 is a guard: the arm only applies when the condition holds. The star is there because we match on a reference.Patterns also work on tuples and structs, with .. to skip fields you do not need. You can combine several patterns with |.
struct Trade { id: u32, notional: f64, currency: &'static str,} fn main() { let trade = Trade { id: 3, notional: 2e6, currency: "EUR" }; let Trade { notional, currency, .. } = trade; println!("{notional} {currency}"); let zone = match currency { "EUR" | "CHF" => "Europe", "USD" | "CAD" => "Amérique du Nord", _ => "autre", }; println!("{zone} (trade {})", trade.id);}When only one case matters, if let saves you from writing a match with an empty _ => {} arm. let ... else does the opposite: it extracts the value or leaves the function right away.
fn spread(bid: Option<f64>, ask: Option<f64>) -> Option<f64> { let Some(b) = bid else { return None }; let Some(a) = ask else { return None }; Some(a - b)} fn main() { if let Some(s) = spread(Some(151.2), Some(151.3)) { println!("spread : {s:.2}"); } println!("{:?}", spread(None, Some(151.3))); // None}Your turn
Complete payoff so it returns an option's payoff at maturity: max(spot - strike, 0) for a Call, max(strike - spot, 0) for a Put.
enum OptionContract { Call { strike: f64 }, Put { strike: f64 },} fn payoff(option: &OptionContract, spot: f64) -> f64 { todo!()} fn main() { println!("{}", payoff(&OptionContract::Call { strike: 100.0 }, 112.0)); // 12 println!("{}", payoff(&OptionContract::Put { strike: 100.0 }, 112.0)); // 0}A match option with one arm per variant; each arm extracts strike.
enum OptionContract { Call { strike: f64 }, Put { strike: f64 },} fn payoff(option: &OptionContract, spot: f64) -> f64 { match option { OptionContract::Call { strike } => (spot - strike).max(0.0), OptionContract::Put { strike } => (strike - spot).max(0.0), }} fn main() { println!("{}", payoff(&OptionContract::Call { strike: 100.0 }, 112.0)); // 12 println!("{}", payoff(&OptionContract::Put { strike: 100.0 }, 112.0)); // 0}Here strike is an &f64 (we match on a reference), yet spot - strike compiles: arithmetic operators are implemented between f64 and &f64.