Traits et génériques
Trait objects et dyn
Les génériques fixent le type à la compilation : un Vec<T> ne contient qu'un seul type T. Pour une liste qui mélange des forwards et des calls, on utilise un trait object : Box<dyn Priced>. Le dyn signale que la méthode à appeler sera choisie à l'exécution, via une table de méthodes (le dispatch dynamique).
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 place la valeur sur le tas : nécessaire car un Forward et un Call n'ont pas forcément la même taille en mémoire. On reviendra sur Box avec les smart pointers.Génériques ou dyn ? Les génériques sont plus rapides (appel direct, inlining possible) mais un seul type à la fois. dyn accepte des types mélangés au prix d'une indirection par appel. Dans un moteur de calcul, on garde les génériques dans les boucles chaudes et dyn pour la configuration (choisir un modèle au démarrage).
À toi de jouer
Écris book_value(book: &[Box<dyn Priced>], spot: f64) -> f64 qui additionne les prix de tous les instruments du 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}On appelle price sur un Box<dyn Priced> exactement comme sur la valeur elle-même.
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}La fonction prend &[Box<dyn Priced>] plutôt que &Vec<...>, toujours la même règle : accepter la slice, plus générale. +10 et -10 se compensent : le book vaut 0 à 110.