Skip to content

Accept a Slice at a Read-Only Boundary

The Course
•
26 min study

Many functions in the reading queue only need to look at a list: total the pages, count the long books, find a title. If such a function takes &Vec<u32>, it only accepts a whole vector. A caller holding an array, or wanting to total only the last three entries, has to build a new Vec first. The beginner planner already exposed a shared &[Session]; today you see why that signature is the better one.

The type &[T] is a slice: a borrowed view of elements stored next to each other. It is just a pointer to the first element plus a length, so creating one copies nothing. A function taking &[u32] can read from an array, a Vec, or any range inside either, and the caller keeps ownership the whole time. When you pass &vector where a slice is expected, Rust converts the &Vec<u32> to &[u32] automatically.

Predict and run

Which call reads fewer elements? What stays available after both calls?

Predict, then run Rust
fn total(pages: &[u32]) -> u32 {
    let mut sum = 0;
    for page in pages {
        sum += *page;
    }
    sum
}

fn main() {
    let array = [20, 15, 5];
    let vector = vec![20, 15, 5];
    println!("Array: {}", total(&array));
    println!("Suffix: {}", total(&vector[1..]));
    println!("Still stored: {}", vector.len());
}
Check your prediction
Text
Array: 40
Suffix: 20
Still stored: 3

&vector[1..] starts at index 1 and runs to the end, so total sees only 15 and 5. Looping over a slice yields &u32 references, which is why the body writes *page. Neither call took ownership, so vector is still usable. Change the range to [..1] and predict the total before you run.

Ranges, bounds and get

A range is written start..end, and the end is excluded. Either side can be left out: [..2] is indices 0 and 1, [1..] is index 1 onward, and [..] is everything. A start equal to the length is allowed and gives an empty slice. A start past the length is a bug, and the program stops:

Text
range start index 5 out of range for slice of length 3

That panic is right when the index comes from your own code and a bad value means a mistake. When the index comes from a user, it is ordinary bad input, and get turns it into an Option instead.

Take a range from user input safely Rust
fn total(pages: &[u32]) -> u32 {
    let mut sum = 0;
    for page in pages {
        sum += *page;
    }
    sum
}

fn main() {
    let pages = vec![20, 15, 5];
    for start in [0, 2, 3, 5] {
        match pages.get(start..) {
            Some(rest) => println!("From {start}: {} pages, {} left", total(rest), rest.len()),
            None => println!("From {start}: no such position"),
        }
    }
}
Text
From 0: 40 pages, 3 left
From 2: 5 pages, 1 left
From 3: 0 pages, 0 left
From 5: no such position

Start 3 equals the length, so it is a valid, empty slice and total returns 0. Start 5 is past the end, so get returns None and total is never called. The same works for a single element: pages.get(7) is None where pages[7] would panic.

Changing elements through a slice

A &mut [T] slice lets a function change elements in place, still without owning them. It cannot add or remove elements, because a slice has a fixed length; only the owning Vec can grow.

Cap page counts in part of a list Rust
fn cap(pages: &mut [u32], limit: u32) {
    for page in pages {
        if *page > limit {
            *page = limit;
        }
    }
}

fn main() {
    let mut pages = vec![620, 90, 800, 130];
    cap(&mut pages[1..], 500);
    println!("{pages:?}");
}
Text
[620, 90, 500, 130]

Only the suffix was capped, so the first entry kept 620. Looping over a &mut [u32] yields &mut u32, and *page = limit writes through it.

Ask for the least you need

For a read-only list parameter, write &[T], not &Vec<T>. For text, write &str, not &String. The smaller type accepts more callers and promises the function will not grow or reallocate anything.

Practice

Exercise

Your turn

Write count_long(pages: &[u32]) -> usize that counts entries of at least 100 pages. Call it on the whole array [90, 100, 130], on its first two entries, and on the empty slice &pages[3..]. Expected output: All: 2, First two: 1, None left: 0.

Your working space Rust
fn main() {
    let pages = [90, 100, 130];
    // Use the same function for the full slice, &pages[..2] and &pages[3..].
    println!("{pages:?}");
}
Hint 1: the idea

The function only reads the elements in the view it receives. It does not need to know whether they came from an array or a vector.

Hint 2: a first step

Start with let mut count = 0; and loop with for value in pages. Remember that value is a reference, so compare *value >= 100.

Worked solution
Run the solution Rust
fn count_long(pages: &[u32]) -> usize {
    let mut count = 0;
    for value in pages {
        if *value >= 100 {
            count += 1;
        }
    }
    count
}

fn main() {
    let pages = [90, 100, 130];
    println!("All: {}", count_long(&pages));
    println!("First two: {}", count_long(&pages[..2]));
    println!("None left: {}", count_long(&pages[3..]));
}
Text
All: 2
First two: 1
None left: 0

[..2] covers indices 0 and 1, because the end is excluded, and 100 counts as long because the test is >=. &pages[3..] is empty but valid, so the loop simply runs zero times. The next lesson applies the same idea to text: a &str is a slice of a string, and a function can return one.

Was this article helpful?

Your response is saved on this device.