Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Primitive Types

Rust slices: the [T] type

Reference for Rust slices: the unsized [T] type, &[T] and &mut [T] views, range slicing, split_at_mut, fat pointers, panics and slice patterns.

A slice is a view into a contiguous run of elements. The type [T] has no length known to the compiler, so you can never hold one by value; you always use it behind a pointer: &[T] (shared), &mut [T] (exclusive), Box<[T]> or Rc<[T]>. A reference to a slice is a "fat pointer" made of an address and a length.

Slices are how Rust code accepts "some elements" without caring where they live. An array, a Vec<T>, a part of either, and even a String's bytes can all be passed to a function that takes &[T].

Rust
let v = vec![1, 2, 3, 4, 5];
let middle: &[i32] = &v[1..4];

Try it

Rust Slicing arrays and vectors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Mutable slices and slice patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
&v[a..b]      // elements a up to (not including) b
&v[a..=b]     // a through b
&v[..]        // everything
&mut v[a..]   // mutable view
let s: &[T] = &array;           // coercion from &[T; N] or &Vec<T>
Part Description
a, b usize positions. Either may be omitted.
Result &[T] or &mut [T], borrowing the original for as long as the slice is alive.

Panics: &v[a..b] panics if a > b or b > len. get(range) returns None instead, and get_mut does the same for mutable access.

Usage notes

  • Take &[T] in parameters rather than &Vec<T> or &[T; N]: callers can pass any of them, and the function still reads the elements the same way.
  • Borrowing rules apply. While a slice of a Vec exists you cannot push to the vector, because that may reallocate and leave the slice dangling. The compiler enforces this.
  • Disjoint mutable access: split_at_mut, chunks_mut, split_first_mut and iter_mut give several &mut pieces that provably do not overlap. Two &mut v[..] expressions do not compile.
  • Zero-length slices are valid: &v[len..] is an empty slice and does not panic.
  • str is a slice too. &str is a view into UTF-8 bytes, and slicing it by byte range panics if you cut inside a character (see str).
  • Sorting, searching and chunking are all slice methods: sort, binary_search, windows and chunks.
  • Owned boxed slices: Vec::into_boxed_slice gives a Box<[T]> that drops spare capacity.
  • Equality and order compare element by element, so [1, 2][..] == vec![1, 2][..] works across array and vector sources.