Sub topic 1
Rust Slices: Contiguous Storage
Prerequisites
Assume basic Rust syntax, ownership, borrowing, arrays, and Vec<T>. A slice is a borrowed view, so ownership rules still apply.
Contiguous storage: arrays and vectors
An array, [T; N], stores exactly N values next to each other in memory. Its length is part of its type:
let array = [10, 20, 30, 40, 50];A vector, Vec<T>, also stores values contiguously, but it owns heap storage that can grow or shrink:
let vector = vec![10, 20, 30, 40, 50];Both containers can be viewed through a slice.
What a slice is
A slice, written &[T], is a borrowed reference to part or all of contiguous data. It does not own the elements and does not copy them. The same slice type can refer to an array, a vector, or another slice.
fn print_values(values: &[i32]) {
println!("{values:?}");
}
fn main() {
let array = [1, 2, 3];
let vector = vec![4, 5, 6];
print_values(&array);
print_values(&vector);
}This function is flexible because it accepts different owners while borrowing their elements.
Creating slices with ranges
Range syntax selects a portion without copying it. The start is included, and the end is excluded.
fn main() {
let data = [10, 20, 30, 40, 50];
let middle = &data[1..4];
println!("{middle:?}");
println!("length: {}", middle.len());
}This prints [20, 30, 40] and length: 3. Common forms include [..] for the whole collection, [start..] from an index to the end, and [..end] from the beginning to an index.
Out-of-range access: indexing vs get
Indexing with slice[index] or slice[range] checks bounds and panics if the request is invalid. Use it when invalid input indicates a programming error.
The get method returns Option, so invalid access can be handled without a panic.
| Operation | Result for invalid access |
|---|---|
| `data[5]` | Panics |
| `data.get(5)` | Returns `None` |
fn main() {
let data = [10, 20, 30];
assert_eq!(data[1], 20);
assert_eq!(data.get(5), None);
assert_eq!(data.get(1..3), Some(&[20, 30][..]));
}Exercise
What type does &data[1..4] have when data is an array of i32?
Show answer
It has type &[i32], a borrowed slice containing three elements.