Slice (Rust)

A slice is a borrowed view into a contiguous part of a collection, written &[T] for arrays/vectors or &str for strings. It references existing data without owning or copying it.

Rust

A slice is a 'fat pointer' — a pointer plus a length — that lets you refer to a sub-range of a Vec, array, or String. You create one with range syntax: &v[1..4] gives elements at indices 1, 2, and 3. Slices never own their data; the original collection does.

Because a slice is just a borrow, the borrow checker ensures the underlying data stays alive and unchanged while the slice exists. This is why you can't hold a slice and mutate the source at the same time.

Writing functions that take &[T] or &str instead of &Vec<T> or &String makes them more general: they then accept arrays, vectors, and other slices alike. Slices are how Rust passes 'a window of data' cheaply and safely.

Syntax

let v = vec![1, 2, 3, 4];
let middle = &v[1..3]; // [2, 3]

Examples

Rust

fn sum(slice: &[i32]) -> i32 {
    slice.iter().sum()
}

fn main() {
    let nums = [10, 20, 30, 40];
    println!("{}", sum(&nums[1..3]));
}

Output:

50

Learn it in a lesson

See also

Back to the Dictionary