Raw data, clear context.

[
[
[

]
]
]

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.

Array indices 0 to 4 contain 4, 7, 2, 9 and 5. The slice 1..4 spans indices 1, 2 and 3, selecting 7, 2 and 9. Index 4 is excluded. The selected values total 18.
The coloured bracket begins at index 1 and stops before index 4. The three highlighted cells remain part of the original array.

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.

src/main.rs
Rust
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));
}
Shell
cargo run --quiet
Output
$ cargo run --quiet
Middle: [7, 2, 9], total 18
Last two: [9, 5], total 14
exit=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

Sources

  1. The Rust Book: The Slice Type
  2. The Rust Reference: Array and index expressions
  3. Rust standard library: Range
  4. Rust standard library: SliceIndex
  5. Rust standard library: slice

Leave a Reply