Ownership and borrowing
Running project · riskforgeProject: aggregate without copying
In real life there are not 5 scenarios but 10,000, and they come in a Vec built at runtime. So we move the logic out of main into functions that borrow the scenarios: no copy, whatever their size.
fn exposure(mtm: f64) -> f64 { mtm.max(0.0)} /// Exposition attendue : moyenne des expositions sur tous les scénarios.fn expected_exposure(mtms: &[f64]) -> f64 { let mut total = 0.0; for &mtm in mtms { total += exposure(mtm); } total / mtms.len() as f64} /// Choc de marché appliqué sur place : chaque MtM bouge du même montant.fn shift(mtms: &mut [f64], amount: f64) { for mtm in mtms.iter_mut() { *mtm += amount; }} fn main() { let mut mtms = vec![1_200.0, -300.0, 450.0, 0.0, -800.0]; println!("EE = {:.2}", expected_exposure(&mtms)); shift(&mut mtms, 200.0); println!("EE après choc = {:.2}", expected_exposure(&mtms));}for &mtm in mtms destructures each &f64 into an f64: possible because f64 is Copy.The signatures tell the story: expected_exposure only reads (&[f64]), shift modifies (&mut [f64]). Just by reading the signatures, a reviewer already knows which functions may touch the data. That is one of Rust's big wins on a large computation engine.
Your turn
Add exposure_profile, which takes the MtMs of several dates (a slice of vectors) and returns a Vec<f64> with the EE of each date.
fn expected_exposure(mtms: &[f64]) -> f64 { let mut total = 0.0; for &mtm in mtms { total += mtm.max(0.0); } total / mtms.len() as f64} fn exposure_profile(dates: &[Vec<f64>]) -> Vec<f64> { todo!()} fn main() { let dates = vec![ vec![100.0, -50.0, 20.0], // 1 an vec![150.0, -80.0, 60.0], // 2 ans vec![90.0, 10.0, -200.0], // 3 ans ]; println!("{:?}", exposure_profile(&dates));}Iterating over dates yields &Vec<f64>, which Rust automatically converts into &[f64] at the call site.
fn expected_exposure(mtms: &[f64]) -> f64 { let mut total = 0.0; for &mtm in mtms { total += mtm.max(0.0); } total / mtms.len() as f64} fn exposure_profile(dates: &[Vec<f64>]) -> Vec<f64> { let mut profile = Vec::new(); for scenarios in dates { profile.push(expected_exposure(scenarios)); } profile} fn main() { let dates = vec![ vec![100.0, -50.0, 20.0], // 1 an vec![150.0, -80.0, 60.0], // 2 ans vec![90.0, 10.0, -200.0], // 3 ans ]; println!("{:?}", exposure_profile(&dates));}The exposure profile (EE at each date) is exactly what a risk manager plots. The automatic conversion from &Vec<f64> to &[f64] is called deref coercion: we will detail it with smart pointers.