Suppose five readings arrived in order and you need the total for the three in the middle. Keep the readings in one array and pass a slice to the function that adds them up.
A shared slice borrows a consecutive stretch of elements from the original array without copying it.[1] Rust counts array and slice indices from zero.[2] In a range written start..end, the start is included and the end is excluded.[3]
In &samples[1..4], the indices are 1, 2 and 3. Their values are 7, 2 and 9. Index 4 is where the slice stops, so the value 5 stays outside this window.

Read &[i32] as a shared reference to a slice of i32 values.[1]
Put the following code in src/main.rs in a Cargo binary project, then run the command from the project directory.
The run below used Cargo 1.99.1 and rustc 1.99.1.
fn total(window: &[i32]) -> i32 { let mut sum = 0; for sample in window { sum += *sample; } sum}fn main() { let samples = [4, 7, 2, 9, 5]; let middle: &[i32] = &samples[1..4]; let last_two: &[i32] = &samples[3..5]; println!("Middle: {middle:?}, total {}", total(middle)); println!("Last two: {last_two:?}, total {}", total(last_two));}
cargo run --quiet
$ cargo run --quietMiddle: [7, 2, 9], total 18Last two: [9, 5], total 14exit=0
The total function receives the slice in window. The loop visits each borrowed reading and *sample reads its value. The first call adds three readings; the second adds two. Since the caller chooses the range, total needs neither the original array nor its indices.
Where the slice stops
For start..end indexing on an array, the start must be at most the end, and the end can be at most the array’s length.[4][5] An empty range at the length is valid and gives an empty slice.[5]
That is why 3..5 selects the last two readings in the example. If you change the middle range to 1..6, the programme panics when it tries to make the slice, before total runs.
When picking a range by hand, check the number of entries before choosing the end. To add up the last three readings instead, work backwards from the length and keep the same end.
Try it
Change 1..4 to 0..2. Predict the two values and their total before running the programme. Leave the second range alone so you can see which output changes.
Next: keeping a list with Vec.
Browse Rust, one step at a time
Leave a Reply