rsRustPrimer
< Back to module

Traits and generics

Generics

A generic function takes a type parameter, written between angle brackets. On its own it can do almost nothing with that unknown type. So you add trait bounds: T: Priced means "any type, as long as it implements Priced". The compiler then checks every call.

rust
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
}
}
// Générique : fonctionne pour tout T qui implémente Priced.
fn price_ladder<T: Priced>(instrument: &T, spots: &[f64]) -> Vec<f64> {
let mut prices = Vec::new();
for &spot in spots {
prices.push(instrument.price(spot));
}
prices
}
// Même chose, syntaxe raccourcie avec impl Trait.
fn mid_price(instrument: &impl Priced, low: f64, high: f64) -> f64 {
(instrument.price(low) + instrument.price(high)) / 2.0
}
fn main() {
let forward = Forward { strike: 100.0 };
println!("{:?}", price_ladder(&forward, &[90.0, 100.0, 110.0]));
println!("{}", mid_price(&forward, 95.0, 115.0));
}

Structs can be generic too, and several bounds combine with +. When the signature gets long, the where clause moves the bounds after the parameters to keep it readable.

rust
use std::fmt::Debug;
#[derive(Debug)]
struct Labeled<T> {
label: String,
value: T,
}
fn report<T>(items: &[Labeled<T>])
where
T: Debug + PartialOrd,
{
for item in items {
println!("{} = {:?}", item.label, item.value);
}
}
fn main() {
let rates = vec![
Labeled { label: String::from("Y"), value: 0.031 },
Labeled { label: String::from("Y"), value: 0.028 },
];
report(&rates);
}

Your turn

Write a generic largest function that returns the largest element of a non-empty slice, for any type T: PartialOrd + Copy.

src/main.rs
fn largest(/* ? */) /* -> ? */ {
todo!()
}
fn main() {
println!("{}", largest(&[3, 17, 5])); // 17
println!("{}", largest(&[0.031, 0.045, 0.028])); // 0.045
}