Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Rust Arrays and Slices: Fixed Arrays, &[T] Fat Pointers, and DSTs

An array carries its length in its type; a slice carries it in the pointer. The split_at_mut, chunks and TryFrom patterns that follow from that.

~4 min readRust
#Rust#Slices#Memory Safety
3D illustration of a fixed stack array contrasted with a fat-pointer slice view over contiguous memory

Quick Summary

[T; N] is a fixed-size array: the length is part of the type, the data lives inline (on the stack when the binding does), and N must be known at compile time. [T] is a slice: an unsized view of a contiguous run of T whose length lives in the pointer. &[T] is therefore a fat pointer — 16 bytes on a 64-bit target, an address plus a length.

That distinction is the whole model. A function taking &[T] accepts arrays, vectors, and sub-ranges of either, because &[T; N] and &Vec<T> both coerce to &[T]. A function taking &[T; N] accepts exactly one length and monomorphises per N. Default to &[T] for parameters and [T; N] for values whose length is part of the meaning (a hash, a UUID, a fixed header).

Slices are dynamically sized types, like str and dyn Trait. You never hold one by value; you hold it behind a reference, a Box, or inside a Vec. The compiler knows the length is carried at runtime, so indexing a slice is bounds-checked — a real check on the slice path, and usually optimized away when the compiler can prove the index is in range.

Basic Syntax & Signature

rust
fn main() { // Array: length in the type, inline storage, Copy when T: Copy. let a: [u8; 4] = [1, 2, 3, 4]; let zeros = [0u8; 32]; assert_eq!(std::mem::size_of_val(&a), 4); assert_eq!(zeros.len(), 32); // Array built from an index function. let squares: [u32; 5] = std::array::from_fn(|i| (i as u32).pow(2)); assert_eq!(squares, [0, 1, 4, 9, 16]); // Array -> slice coercion, explicit or automatic. let s: &[u8] = &a; assert_eq!(s.len(), 4); let mid: &[u8] = &a[1..3]; assert_eq!(mid, [2, 3]); // Slice from a Vec. let v = vec![10, 20, 30, 40]; let tail: &[i32] = &v[2..]; assert_eq!(tail, [30, 40]); // Mutable slice. let mut m = [1, 2, 3]; let mm: &mut [i32] = &mut m; mm[0] = 9; assert_eq!(m, [9, 2, 3]); // Fat pointer: address + length. assert_eq!(std::mem::size_of::<&[u8]>(), 16); assert_eq!(std::mem::size_of::<&[u8; 4]>(), 8); // Iteration: by value (2021), by reference, by mutable reference. for x in a { print!("{x}"); } // u8, copies for x in &a { print!("{x}"); } // &u8 let doubled: Vec<u8> = a.iter().map(|x| x * 2).collect(); assert_eq!(doubled, [2, 4, 6, 8]); println!(); }

The slice API worth knowing by heart:

rust
impl<T> [T] { pub fn len(&self) -> usize; pub fn is_empty(&self) -> bool; pub fn first(&self) -> Option<&T>; pub fn last(&self) -> Option<&T>; pub fn get<I: SliceIndex<[T]>>(&self, index: I) -> Option<&I::Output>; pub fn split_at(&self, mid: usize) -> (&[T], &[T]); pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]); pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T>; pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T>; pub fn windows(&self, size: usize) -> Windows<'_, T>; pub fn binary_search(&self, x: &T) -> Result<usize, usize> where T: Ord; pub fn sort_unstable(&mut self) where T: Ord; } // Fallible conversion from a slice to a fixed array. impl<T: Copy, const N: usize> TryFrom<&[T]> for [T; N] { type Error = TryFromSliceError; }

Key Comparison Table

[T; N]&[T]Vec<T>Box<[T]>
Size known at compile timeYes, in the typeNo (length in pointer)No (len + cap fields)No (length in pointer)
Stack sizeN * size_of::<T>()16 bytes24 bytes16 bytes
GrowableNoNoYesNo
CopyIf T: CopyAlways (the pointer)NoNo
Heap allocationNo (unless boxed)NoYesYes
Element countConst NRuntimeRuntimeRuntime
Typical positionFixed buffers, headers, keysFunction parametersOwned collectionsImmutable owned bytes
OperationCostPanics
&s[i..j]O(1)Yes, if i > j or j > len
s.get(i..j)O(1)No, returns None
s.chunks(k)O(1) per chunkNo
s.windows(k)O(1) per windowNo (empty if k > len)
s.binary_search(x)O(log n)No
s.sort_unstable()O(n log n)No
s.into_iter() on [T; N]O(n)No

Practical Edge Cases & Deep Dives

1. split_at_mut to satisfy the borrow checker

rust
// Fails: cannot borrow `buf` as mutable more than once. // fn split_first_two(buf: &mut [u8]) -> (&mut u8, &mut u8) { // (&mut buf[0], &mut buf[1]) // } fn split_first_two(buf: &mut [u8]) -> Option<(&mut u8, &mut u8)> { if buf.len() < 2 { return None; } let (first, rest) = buf.split_at_mut(1); Some((&mut first[0], &mut rest[0])) } fn main() { let mut buf = [0u8; 4]; let (a, b) = split_first_two(&mut buf).unwrap(); *a = 1; *b = 2; assert_eq!(buf[..2], [1, 2]); }

Two &mut into the same slice is the canonical aliasing violation, and split_at_mut is the safe primitive that proves the two halves are disjoint. The same idea underlies chunks_mut, split_first_mut, and the rayon parallel slice iterators, all of which hand out disjoint mutable references to worker threads.

2. Chunking protocols without copying

rust
fn checksum(packet: &[u8]) -> u8 { packet.iter().fold(0u8, |acc, b| acc.wrapping_add(*b)) } fn parse_frames(bytes: &[u8], frame_len: usize) -> Vec<u8> { // `chunks` drops a short trailing chunk; `chunks_exact` would skip it. bytes.chunks(frame_len).map(checksum).collect() } fn parse_frames_exact(bytes: &[u8], frame_len: usize) -> (Vec<u8>, usize) { let mut sums = Vec::new(); let mut rest = bytes; let mut chunks = bytes.chunks_exact(frame_len); for c in &mut chunks { sums.push(checksum(c)); } rest = chunks.remainder(); (sums, rest.len()) } fn main() { let data = [1u8, 2, 3, 4, 5, 6, 7]; assert_eq!(parse_frames(&data, 3), vec![6, 15, 7]); let (sums, leftover) = parse_frames_exact(&data, 3); assert_eq!(sums, [6, 15]); assert_eq!(leftover, 1); }

chunks_exact plus remainder() is the correct pair for framed protocols: it guarantees every processed chunk is full-size, so a partial frame cannot be misinterpreted as a short packet. windows(2) is the analogous primitive for pairwise comparisons over adjacent elements.

3. TryFrom between slices and fixed arrays

rust
use std::convert::TryFrom; fn header(bytes: &[u8]) -> Option<([u8; 4], &[u8])> { // Fails cleanly when fewer than 4 bytes arrive. let magic = <[u8; 4]>::try_from(bytes.get(..4)?).ok()?; Some((magic, &bytes[4..])) } fn main() { let data = b"RIFFxxxx"; let (magic, body) = header(data).unwrap(); assert_eq!(&magic, b"RIFF"); assert_eq!(body, b"xxxx"); assert!(header(b"RIF").is_none()); // The other direction: an array is a slice via coercion. let arr = [1u8, 2, 3, 4]; let sl: &[u8] = &arr; assert_eq!(sl.len(), 4); // Vec -> Box<[T]> drops the capacity field. let boxed: Box<[u8]> = vec![1, 2, 3].into_boxed_slice(); assert_eq!(&*boxed, &[1, 2, 3]); }

<[u8; 4]>::try_from(slice) is the safe replacement for the old transmute pattern of reading a header. It is Copy-bounded, so it works for [u8; N] but not for a fixed-size array of String — the fallible .try_into() on a &[String] needs T: Copy, which is the limitation to remember.

4. Pattern matching on slices

rust
fn describe(command: &[&str]) -> String { match command { [] => "no command".to_string(), [one] => format!("one: {one}"), [first, rest @ ..] => format!("{} then {} more", first, rest.len()), } } fn split_protocol(line: &[u8]) -> Option<(&[u8], &[u8])> { match line { [b'G', b'E', b'T', b' ', path @ ..] => Some((&b"GET"[..], path)), _ => None, } } fn main() { assert_eq!(describe(&[]), "no command"); assert_eq!(describe(&["run"]), "one: run"); assert_eq!(describe(&["a", "b", "c"]), "a then 2 more"); assert_eq!(split_protocol(b"GET /index"), Some((&b"GET"[..], &b"/index"[..]))); assert_eq!(split_protocol(b"POST /x"), None); }

Slice patterns give a length-aware match with no indexing and no unwrap, and rest @ .. binds the tail as a new slice. [first, .., last] is also legal when the middle is only needed for its existence; ..= is not — the syntax is @ ...

5. DSTs: str, [T], and dyn Trait behind a pointer

rust
trait Shape { fn area(&self) -> f64; } struct Square { side: f64 } impl Shape for Square { fn area(&self) -> f64 { self.side * self.side } } fn total_area(shapes: &[Box<dyn Shape>]) -> f64 { shapes.iter().map(|s| s.area()).sum() } fn main() { // Box<str>: an owned string without a capacity field. let s: Box<str> = "hello".into(); assert_eq!(&*s, "hello"); assert_eq!(std::mem::size_of_val(&*s), 5); // &dyn Trait is a fat pointer: data pointer + vtable pointer. let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Square { side: 2.0 })]; assert_eq!(total_area(&shapes), 4.0); // Generic code that must accept unsized types opts in with ?Sized. fn first_char<T: AsRef<str> + ?Sized>(s: &T) -> Option<char> { s.as_ref().chars().next() } assert_eq!(first_char("abc"), Some('a')); assert_eq!(first_char(&String::from("xyz")), Some('x')); // Arrays of zero length are valid and have zero size. let empty: [u8; 0] = []; assert_eq!(std::mem::size_of_val(&empty), 0); }

Every generic parameter has an implicit Sized bound; ?Sized relaxes it, which is required for &T where T: ?Sized and is why AsRef<str> in the standard library is declared that way. Without it, first_char::<str>(...) cannot be instantiated.

6. Bounds checks and the safe alternatives

rust
fn main() { let v = vec![1, 2, 3]; // Checked: returns Option, never panics. assert_eq!(v.get(1), Some(&2)); assert_eq!(v.get(9), None); // Unchecked: panics with a clear message. let r = std::panic::catch_unwind(|| v[9]); assert!(r.is_err()); // Ranges are checked as a whole, not element by element. assert_eq!(v.get(1..3), Some(&[2, 3][..])); assert_eq!(v.get(2..9), None); assert_eq!(v.get(3..2), None); // start > end is invalid, not empty // first/last replace explicit length arithmetic. if let (Some(&first), Some(&last)) = (v.first(), v.last()) { assert_eq!((first, last), (1, 3)); } // Slicing with a fixed pattern avoids both. if let [a, b, c] = v.as_slice() { assert_eq!(*a + *b + *c, 6); } }

A common performance worry: bounds checks look expensive but rarely are. The compiler removes them when the index is provably in range (a loop over 0..v.len()), and the branch predictor handles the rest. Reaching for get_unchecked to avoid a branch is the wrong first move; measure before trading safety for it.

Common Compilation/Runtime Mistakes

Error / symptomCauseFix
E0308: expected '&[T; 4]', found '&[T]'Function takes a fixed-length referenceAccept &[T], or convert with try_into
panic: index out of boundsIndex outside the slice lengthget, first, pattern match
cannot compare an array with a slice[u8; 4] == &[u8]Compare &a[..] with the slice, or use a.as_slice()
E0502: cannot borrow as mutable more than onceTwo &mut into one slicesplit_at_mut, chunks_mut, split_first_mut
the size for values of type '[T]' cannot be knownSlice stored by valueStore Box<[T]>, Vec<T>, or &[T]
E0277: the size for values of type 'str' is not known in a genericMissing ?SizedT: ?Sized
A [T; N] in a function signature monomorphises per NLength is part of the typeTake &[T] unless the length matters
into_iter() yields references on an arrayEdition 2015 semanticsUse edition 2021, or .iter().copied()
try_into unavailable for &[String]TryFrom<&[T]> for [T; N] needs T: CopyVec, arrayvec, or manual copy
Slice from a Vec danglesReturning &v[..] from a function that owns vReturn Vec<T> or accept a borrowed input

One edition detail that trips people migrating old code: in edition 2015 and 2018, for x in [1, 2, 3] iterated by reference because IntoIterator was only implemented for arrays from 2021 onward. The 2021 for loop yields values. Code that relied on x: &i32 compiles differently after the edition bump, which is why array.into_iter() now has distinct behaviour from array.iter().

Try matching browser tools

All tools

Small utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Rust guides

More in Rust

All Rust guides

The guides filed next to this one in Rust, in library order.