Rust Fundamentals · 15 XP Pro

Slices

A slice is a borrowed view into a run of elements, without owning them. Its type is &[T]. Slices are the idiomatic way to accept "some numbers" in a function, because one parameter type works for whole arrays and for parts of them.

You make a slice with a range inside square brackets:

let data = [10, 20, 30, 40, 50];
let all: &[i32] = &data;      // the whole array
let mid = &data[1..4];        // 20, 30, 40  (end is exclusive)
let head = &data[..2];        // 10, 20
let tail = &data[3..];        // 40, 50

A slice knows its length (len()), can be indexed, and can be looped over with for x in slice. Going out of range panics, so check the length first when it could be small.

Your task

Write two pub functions:

  • sum(values: &[i32]) -> i32 adds up all elements (an empty slice gives 0).
  • middle(values: &[i32]) -> &[i32] returns the slice without its first and last element. If there are fewer than 2 elements, return an empty slice.

For example middle(&[1, 2, 3, 4]) is [2, 3].

Next lesson →

Sign in to run your code. It's free.