Module 6Traits & GenericsLesson 5 of 822 min
Generics & Trait Bounds
One total_payoff for any Payoff type.
Generic function
rust
fn total<P: Payoff>(xs: &[P], spot: f64) -> f64 {
xs.iter().map(|c| c.payoff(spot)).sum()
}Monomorphization
Specialized machine code per concrete type — fast.
Challenge
Weight by qty: sum qty_i * payoff_i.
Tips
- Zero-cost generics
- Bounds after :
- where clauses for complex bounds
Try it live
Generics & Trait BoundsRust 2021
Loading editor…
Output
Press Run to compile and execute.