rsRustPrimer
< Back to module

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
}