Skip to main content
A slice in Rust is a dynamically-sized type (DST) representing a contiguous view into a block of memory. It allows safe, borrow-checked access to a portion of a collection—such as an array, Vec<T>, or String—without copying the underlying data. Because the slice itself ([T]) is dynamically sized, its size is not known at compile time. Consequently, slices are almost exclusively interacted with via references (&[T] for shared access or &mut [T] for mutable access). Under the hood, a slice reference is a “fat pointer” consisting of exactly two machine words:
  1. A pointer to the memory address of the first element in the slice.
  2. A usize representing the length of the slice (the number of elements it contains).

Syntax and Instantiation

Slices are constructed using the borrowing operator (& or &mut) combined with Rust’s range syntax (start..end), where start is inclusive and end is exclusive.
Rust provides syntactic sugar for omitting bounds when slicing from the beginning or to the end of a collection:

String Slices (&str)

A string slice (&str) is a specialized, primitive slice type. While &[T] is a slice of arbitrary elements, &str is fundamentally a slice of bytes (&[u8]) with a strict type system and standard library guarantee that the underlying byte sequence is valid UTF-8.
Note: Slicing a string must occur at valid UTF-8 character boundaries. Slicing in the middle of a multi-byte character will cause a runtime panic.

Type System Mechanics

  • [T]: The slice type itself. It does not implement the Sized trait (making it an unsized type), meaning it cannot be stored directly on the stack or passed by value.
  • &[T]: The slice reference. It implements the Sized trait because the fat pointer has a fixed, known size at compile time (16 bytes on a 64-bit architecture).
  • Deref Coercion: Collections that manage contiguous memory implement the Deref trait targeting their respective slice types. Vec<T> implements Deref<Target = [T]>, and String implements Deref<Target = str>. This allows a &Vec<T> to implicitly coerce into a &[T] when passed to functions or methods.
Tired of Poor Rust Skills? Fix That With Deep Grasping!Learn More