Traits et génériques
Définir et implémenter un trait
Un trait décrit un comportement : une liste de méthodes qu'un type s'engage à fournir. C'est proche d'une interface Java ou Kotlin, à une différence près : on peut implémenter un trait pour un type après coup, dans un bloc impl Trait for Type séparé de la déclaration du type.
trait Priced { fn price(&self, spot: f64) -> f64; // Méthode par défaut : les types peuvent la garder ou la redéfinir. fn describe(&self) -> String { String::from("instrument") }} 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 describe(&self) -> String { format!("call {}", self.strike) }} fn main() { let forward = Forward { strike: 100.0 }; let call = Call { strike: 105.0 }; println!("{} : {}", forward.describe(), forward.price(110.0)); println!("{} : {}", call.describe(), call.price(110.0));}On peut aussi implémenter ses propres traits pour des types qu'on n'a pas écrits, comme f64 ou Vec<T>. La seule limite, la règle d'orphelin : le trait ou le type doit venir de ton crate. Tu ne peux pas implémenter Display (de la bibliothèque standard) pour Vec (de la bibliothèque standard).
trait Percent { fn as_percent(&self) -> String;} impl Percent for f64 { fn as_percent(&self) -> String { format!("{:.2} %", self * 100.0) }} fn main() { println!("{}", 0.0315.as_percent()); // 3.15 %}À toi de jouer
Ajoute une struct Put { strike: f64 } qui implémente Priced : son prix vaut max(strike - spot, 0) et sa description "put <strike>".
trait Priced { fn price(&self, spot: f64) -> f64; fn describe(&self) -> String { String::from("instrument") }} // ajoute Put et son impl ici fn main() { let put = Put { strike: 100.0 }; println!("{} : {}", put.describe(), put.price(92.0)); // put 100 : 8}Seule price est obligatoire ; redéfinis describe pour remplacer le texte par défaut.
trait Priced { fn price(&self, spot: f64) -> f64; fn describe(&self) -> String { String::from("instrument") }} struct Put { strike: f64,} impl Priced for Put { fn price(&self, spot: f64) -> f64 { (self.strike - spot).max(0.0) } fn describe(&self) -> String { format!("put {}", self.strike) }} fn main() { let put = Put { strike: 100.0 }; println!("{} : {}", put.describe(), put.price(92.0)); // put 100 : 8}Si tu oublies price, l'erreur est explicite : not all trait items implemented, missing: price. Le trait est un contrat vérifié à la compilation.