rsRustPrimer
< Retour au module

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.

rust
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).

rust
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>".

src/main.rs
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
}