Traits and generics
Defining and implementing a trait
A trait describes behavior: a list of methods a type commits to provide. It is close to a Java or Kotlin interface, with one difference: you can implement a trait for a type after the fact, in an impl Trait for Type block separate from the type declaration.
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));}You can also implement your own traits for types you did not write, like f64 or Vec<T>. The only limit, the orphan rule: either the trait or the type must come from your crate. You cannot implement Display (from the standard library) for Vec (from the standard library).
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 %}Your turn
Add a Put { strike: f64 } struct implementing Priced: its price is max(strike - spot, 0) and its 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}Only price is required; override describe to replace the default text.
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}If you forget price, the error is explicit: not all trait items implemented, missing: price. The trait is a contract checked at compile time.