Traits and generics
Trait objects and dyn
Generics fix the type at compile time: a Vec<T> holds a single type T. For a list that mixes forwards and calls, you use a trait object: Box<dyn Priced>. The dyn signals that the method to call will be picked at runtime, through a method table (dynamic dispatch).
trait Priced { fn price(&self, spot: f64) -> f64;} struct Forward { strike: f64,}struct Call { strike: f64,} impl Priced for Forward { fn price(&self, spot: f64) -> f64 { spot - self.strike }}impl Priced for Call { fn price(&self, spot: f64) -> f64 { (spot - self.strike).max(0.0) }} fn main() { let book: Vec<Box<dyn Priced>> = vec![ Box::new(Forward { strike: 100.0 }), Box::new(Call { strike: 105.0 }), Box::new(Call { strike: 115.0 }), ]; let mut total = 0.0; for instrument in &book { total += instrument.price(110.0); } println!("valeur du book : {total}"); // 10 + 5 + 0 = 15}Box puts the value on the heap: needed because a Forward and a Call do not necessarily have the same size in memory. We will come back to Box with smart pointers.Generics or dyn? Generics are faster (direct call, inlining possible) but one type at a time. dyn accepts mixed types at the cost of one indirection per call. In a computation engine, keep generics in hot loops and dyn for configuration (picking a model at startup).
Your turn
Write book_value(book: &[Box<dyn Priced>], spot: f64) -> f64, which sums the prices of every instrument in the book.
trait Priced { fn price(&self, spot: f64) -> f64;} struct Forward { strike: f64,} impl Priced for Forward { fn price(&self, spot: f64) -> f64 { spot - self.strike }} fn book_value(book: &[Box<dyn Priced>], spot: f64) -> f64 { todo!()} fn main() { let book: Vec<Box<dyn Priced>> = vec![ Box::new(Forward { strike: 100.0 }), Box::new(Forward { strike: 120.0 }), ]; println!("{}", book_value(&book, 110.0)); // 0}You call price on a Box<dyn Priced> exactly as on the value itself.
trait Priced { fn price(&self, spot: f64) -> f64;} struct Forward { strike: f64,} impl Priced for Forward { fn price(&self, spot: f64) -> f64 { spot - self.strike }} fn book_value(book: &[Box<dyn Priced>], spot: f64) -> f64 { let mut total = 0.0; for instrument in book { total += instrument.price(spot); } total} fn main() { let book: Vec<Box<dyn Priced>> = vec![ Box::new(Forward { strike: 100.0 }), Box::new(Forward { strike: 120.0 }), ]; println!("{}", book_value(&book, 110.0)); // 0}The function takes &[Box<dyn Priced>] rather than &Vec<...>, the same rule as always: accept the slice, which is more general. +10 and -10 cancel out: the book is worth 0 at 110.