Ownership and borrowing
Slices
A slice is a reference to a contiguous portion of a collection: a pointer and a length, no copy. &[f64] is a view over f64 values, &str a view over text.
rust
fn main() { let curve = vec![0.010, 0.015, 0.021, 0.026, 0.030]; let short_end: &[f64] = &curve[..2]; // indices 0 et 1 let long_end = &curve[3..]; // de 3 à la fin println!("{short_end:?} {long_end:?}"); let isin = String::from("FR0000131104"); let country: &str = &isin[..2]; println!("pays : {country}");}The main benefit: writing functions that accept the most general type. A function taking &[f64] accepts an array, a Vec, or a piece of either. A function taking &str accepts a String as well as a literal.
rust
fn total(values: &[f64]) -> f64 { let mut sum = 0.0; for v in values { sum += v; } sum} fn main() { let fixed = [1.0, 2.0, 3.0]; let dynamic = vec![4.0, 5.0, 6.0, 7.0]; println!("{} {} {}", total(&fixed), total(&dynamic), total(&dynamic[1..3]));}Your turn
Write average, which takes a slice of f64 and returns its mean, then call it on the last 3 elements of the vector.
src/main.rs
fn average(/* ? */) -> f64 { todo!()} fn main() { let prices = vec![100.0, 101.0, 99.0, 102.0, 104.0, 103.0]; // moyenne des 3 derniers : 103}The range [len - 3..] goes from the third-to-last element to the end.
solution
fn average(values: &[f64]) -> f64 { let mut sum = 0.0; for v in values { sum += v; } sum / values.len() as f64} fn main() { let prices = vec![100.0, 101.0, 99.0, 102.0, 104.0, 103.0]; let last_three = &prices[prices.len() - 3..]; println!("{}", average(last_three)); // 103}No data is copied: last_three is just a pointer and a length. Beware, an empty slice would give 0 / 0 = NaN; we will handle that case properly with Option in the error-handling module.