rsRustPrimer
< Back to module

Collections

Vec<T>

Vec<T> is an array that grows at runtime, the equivalent of a Java ArrayList. Its elements sit next to each other in memory, which makes it very fast to iterate. You create it empty with Vec::new() or filled with the vec! macro.

rust
fn main() {
let mut prices: Vec<f64> = Vec::new();
prices.push(101.5);
prices.push(99.8);
prices.push(103.2);
let tenors = vec![1, 2, 5, 10];
println!("{} prix, {} tenors", prices.len(), tenors.len());
let last = prices.pop(); // Option<f64> : le Vec peut être vide
println!("{last:?} retiré, reste {prices:?}");
}

Two ways to read an element. Indexing v[i] returns the value directly but panics if i is out of bounds. v.get(i) returns an Option: Some(&value) or None. Use indexing when going out of bounds would be a bug, and get when absence is a normal case.

rust
fn main() {
let curve = vec![0.010, 0.015, 0.021];
println!("{}", curve[1]);
match curve.get(10) {
Some(rate) => println!("taux : {rate}"),
None => println!("pas de point à cet indice"),
}
let mut shocked = curve.clone();
for rate in shocked.iter_mut() {
*rate *= 2.0;
}
println!("{shocked:?}"); // [0.02, 0.03, 0.042]
}

A classic trap: sort() does not work on a Vec<f64>. Floats have no total order because of NaN (NaN is neither smaller nor greater than 1.0). So you sort with sort_by and the f64::total_cmp function, which defines a complete order, NaN included.

rust
fn main() {
let mut exposures = vec![450.0, 1_200.0, 0.0, 330.0];
// exposures.sort(); // erreur : the trait `Ord` is not implemented for `f64`
exposures.sort_by(f64::total_cmp);
println!("{exposures:?}");
let mut ids = vec![42, 7, 19];
ids.sort(); // les entiers ont un ordre total : sort() suffit
println!("{ids:?}");
}

Your turn

Write percentile, which sorts a copy of the values and returns the one at position p (between 0 and 1). This is the basis of PFE, which is a high percentile of exposures.

src/main.rs
fn percentile(values: &[f64], p: f64) -> f64 {
todo!()
}
fn main() {
let exposures = [0.0, 50.0, 330.0, 120.0, 1_200.0, 80.0, 450.0, 0.0, 60.0, 900.0];
println!("{}", percentile(&exposures, 0.9)); // 1200
println!("{}", percentile(&exposures, 0.5)); // 120
}