Sub topic 11
Under the hood: fat pointers and unsized types
This chapter explains how a slice reference is stored in memory and why Rust treats [T], str, and dyn Trait differently from ordinary types. It assumes you can create slices with ranges, know the difference between &[T] and Vec<T>, and understand basic borrowing. You don't need unsafe Rust.
Sized and unsized types
Most types have a size the compiler knows at compile time. i32 is 4 bytes. [i32; 5] is 20 bytes. A struct is the sum of its fields plus padding. These types implement the marker trait Sized.
Some types have no size known at compile time:
[T], a run ofTvalues of unknown length.str, a run of UTF-8 bytes of unknown length.dyn Trait, some concrete type that implementsTrait, where the compiler doesn't know which one.
These are called dynamically sized types (DSTs). The type [i32] without a reference or box is not a slice reference. It is the sequence of elements itself, and its length is part of the value, not the type.
That has direct consequences. You can't write let x: [i32] = ..., because the compiler wouldn't know how much stack space to reserve. You can't pass a bare str to a function or return it. A DST can only be used behind a pointer: &[T], &mut [T], &str, Box<[T]>, Rc<str>, &dyn Trait, and so on.
Every generic parameter has an implicit T: Sized bound. To accept a DST you have to opt out with ?Sized, which is covered below.
Fat pointers
A reference to a Sized type is a single machine address, called a thin pointer. A reference to a DST needs one more piece of information, called metadata, so the pointer is twice as wide. It is called a fat pointer.
| Pointer type | Contents | Metadata |
|---|---|---|
| `&T`, `&mut T` (sized `T`) | address | none |
| `&[T]`, `&mut [T]` | address of first element, length | number of elements |
| `&str` | address of first byte, length | number of bytes |
| `&dyn Trait` | address of value, vtable pointer | table of methods and type size |
Note that the length of a slice is counted in elements, while the length of a str is counted in bytes. This is why &s[0..2] on a string can fail on a character boundary, as covered in the string slices chapter.
The sizes are easy to check:
use std::fmt::Debug;
use std::mem::size_of;
fn main() {
let w = size_of::<usize>();
assert_eq!(size_of::<&i32>(), w);
assert_eq!(size_of::<&[i32; 5]>(), w);
assert_eq!(size_of::<&[i32]>(), 2 * w);
assert_eq!(size_of::<&mut [i32]>(), 2 * w);
assert_eq!(size_of::<&str>(), 2 * w);
assert_eq!(size_of::<&dyn Debug>(), 2 * w);
assert_eq!(size_of::<Box<[i32]>>(), 2 * w);
// Vec currently stores pointer, capacity, and length.
println!("&[i32] is {} bytes, Vec<i32> is {} bytes", size_of::<&[i32]>(), size_of::<Vec<i32>>());
}On a 64-bit target, &i32 is 8 bytes and &[i32] is 16. Notice that &[i32; 5] is only 8 bytes. The array type already carries its length, so no metadata is needed.
What slicing actually does
Creating a subslice copies no elements. It computes a new address and a new length and builds a new fat pointer. For &whole[1..4] the compiler checks 1 <= 4 <= whole.len(). If the check passes, it creates a pointer whole.as_ptr() + 1 with length 4 - 1.
fn main() {
let a = [10, 20, 30, 40, 50];
let whole: &[i32] = &a;
let part = &whole[1..4];
println!("whole: ptr={:p} len={}", whole.as_ptr(), whole.len());
println!("part: ptr={:p} len={}", part.as_ptr(), part.len());
assert!(std::ptr::eq(part.as_ptr(), &a[1]));
assert_eq!(part.len(), 3);
}The part pointer is exactly one i32 (4 bytes) after the whole pointer. The exact addresses vary between runs, but the 4-byte difference does not.
This is why slicing is cheap, and why first_word-style functions can return a slice of their input at no cost. The returned value is two words, whatever the size of the data it describes.
Unsized coercion: from array to slice
An array reference becomes a slice reference through unsized coercion. The compiler takes the length out of the type and puts it into the pointer's metadata:
&[i32; 5] (thin, length is in the type)
becomes
&[i32] (fat, length is a runtime value)This is why you can pass &[1, 2, 3] to a function taking &[i32]. It also works with Box<[i32; 3]> to Box<[i32]>. The conversion goes one way only. To get an array back from a slice you need a fallible conversion such as <&[i32; 3]>::try_from(slice), because the slice length is only known at runtime.
A related conversion is deref coercion. &Vec<T> becomes &[T] and &String becomes &str because Vec<T>: Deref<Target = [T]> and String: Deref<Target = str>. This is a call to deref, not an unsizing step. It reads the vector's pointer and length fields and builds a fat pointer from them.
Writing code that accepts unsized types
A generic parameter is Sized by default, so fn show<T: Debug>(value: &T) rejects str and [i32] as T, even though the parameter is a reference. Adding ?Sized relaxes the bound:
use std::fmt::Debug;
fn show<T: ?Sized + Debug>(value: &T) {
println!("{:?} occupies {} bytes", value, std::mem::size_of_val(value));
}
fn main() {
show("héllo");
show(&[1, 2, 3][..]);
show(&42u8);
}This prints "héllo" occupies 6 bytes (five characters, with é taking two bytes), then [1, 2, 3] occupies 12 bytes, then 42 occupies 1 bytes.
size_of_val reads the metadata to compute the size. For a slice it multiplies the length by the element size. size_of::<T>() would not compile for an unsized T, because there is no single answer.
The ?Sized bound can only appear where the type is used behind a pointer. Inside the function you can't move T by value, return it, or store it in a local variable.
Owning unsized data
A reference is not the only way to point at a DST. Several owning pointers can hold one, and each is also a fat pointer:
| Type | Owns | Notes |
|---|---|---|
| `Box<[T]>` | a heap buffer with fixed length | 2 words, no spare capacity |
| `Box<str>` | UTF-8 text with fixed length | 2 words |
| `Rc<[T]>`, `Arc<[T]>` | shared, reference-counted buffer | cheap to clone, immutable |
| `Rc<str>`, `Arc<str>` | shared text | common for interned names |
Box<[T]> is a Vec<T> without the capacity field. It is useful when a collection is built once and never grows, because it is a word smaller and states that intent in the type. The conversions are cheap:
use std::rc::Rc;
fn main() {
let v = vec![1, 2, 3];
let boxed: Box<[i32]> = v.into_boxed_slice();
println!("boxed len = {}", boxed.len());
let back: Vec<i32> = boxed.into_vec();
let shared: Rc<[i32]> = Rc::from(back);
let other = Rc::clone(&shared);
println!("{:?} count = {}", other, Rc::strong_count(&shared));
let name: Box<str> = "hello".into();
println!("{} has {} bytes", name, name.len());
}into_boxed_slice shrinks the allocation to fit if the vector has spare capacity, which may reallocate. into_vec reuses the buffer without copying. Rc::from(vec) allocates a new block that holds the reference counts followed by the elements, then copies the elements into it.
Edge cases and limits
- Empty slices. An empty slice has length 0 and a valid, non-null, aligned address. It does not necessarily point at real data, so never compare slice addresses to decide whether two slices are "the same".
- Zero-sized elements. A
&[()]can have a length of a million and still describe zero bytes. The length is stored, and the address is irrelevant. - Maximum size. No single object can be larger than
isize::MAXbytes, so a slice length is always small enough that its byte size fits in anisize. - Aliasing. A
&mut [T]is exclusive. The compiler may assume nothing else reads or writes the same elements while it exists. This is the reasonsplit_at_mutis needed to get two mutable views, and why it is implemented with unsafe code behind a safe interface. - Trait objects. A
&dyn Traitis also a fat pointer, but its metadata is a vtable pointer rather than a length. You can't turn it into a slice, and a slice pointer can't be turned into a trait object pointer of a different kind.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `the size for values of type [i32] cannot be known at compilation time` | A local, parameter, or return value has a bare DST type | Put it behind `&`, `&mut`, or `Box` |
| `the size for values of type str cannot be known` in a generic function | The implicit `T: Sized` bound | Declare `T: ?Sized` |
| Mismatched types: expected `[i32; 3]`, found `&[i32]` | Trying to treat a slice as an array | Use `try_into()` for a checked conversion, or copy with `to_vec()` |
| `Box<[T]>` result is slower to grow than expected | It has no spare capacity | Convert back with `into_vec()` before pushing |
Summary
- A slice type
[T]is unsized, so you only ever use it behind a pointer. - Pointers to unsized types are fat. For slices and
strthe extra word is a length. Fordyn Traitit is a vtable. - Slicing builds a new address and length without copying data.
- Array references coerce to slice references, and
&Vec<T>and&Stringcoerce throughDeref. - Use
?Sizedto write generic code that acceptsstrand[T]. Box<[T]>,Rc<[T]>, andBox<str>own unsized data with a fat pointer.
Exercise
On a 64-bit target, what are the sizes in bytes of &i32, &[i32; 4], &[i32], and Box<str>, and why do they differ?
Show answer
&i32 is 8 bytes and &[i32; 4] is also 8 bytes, because both point at a type of known size. The array's length (4) is part of its type, so no metadata is needed. &[i32] is 16 bytes because it stores the address and a runtime length. Box<str> is also 16 bytes: an address plus the byte length of the text.
Exercise
Why does fn describe<T: Debug>(x: &T) reject describe("hi")... or does it? Explain what happens with describe("hi") and with describe(&[1, 2][..]), and what single change makes both calls work.
Show answer
Passing "hi" has type &str, so the compiler infers T = str. That is an unsized type, and the implicit T: Sized bound rejects it. The same happens with &[1, 2][..], which would need T = [i32]. Changing the signature to fn describe<T: ?Sized + Debug>(x: &T) removes the implicit bound, and both calls compile.