rsRustPrimer
< Back to module

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.

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));
}

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

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 %
}

Your turn

Add a Put { strike: f64 } struct implementing Priced: its price is max(strike - spot, 0) and its 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
}