rsRustPrimer
< Back to module

Traits and generics

Trait objects and dyn

Generics fix the type at compile time: a Vec<T> holds a single type T. For a list that mixes forwards and calls, you use a trait object: Box<dyn Priced>. The dyn signals that the method to call will be picked at runtime, through a method table (dynamic dispatch).

rust
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 puts the value on the heap: needed because a Forward and a Call do not necessarily have the same size in memory. We will come back to Box with smart pointers.

Generics or dyn? Generics are faster (direct call, inlining possible) but one type at a time. dyn accepts mixed types at the cost of one indirection per call. In a computation engine, keep generics in hot loops and dyn for configuration (picking a model at startup).

Your turn

Write book_value(book: &[Box<dyn Priced>], spot: f64) -> f64, which sums the prices of every instrument in the book.

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