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,Documentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
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:
- A pointer to the memory address of the first element in the slice.
- A
usizerepresenting 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.
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.
Type System Mechanics
[T]: The slice type itself. It does not implement theSizedtrait (making it an unsized type), meaning it cannot be stored directly on the stack or passed by value.&[T]: The slice reference. It implements theSizedtrait 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
Dereftrait targeting their respective slice types.Vec<T>implementsDeref<Target = [T]>, andStringimplementsDeref<Target = str>. This allows a&Vec<T>to implicitly coerce into a&[T]when passed to functions or methods.
Master Rust with Deep Grasping Methodology!Learn More





