Sub topic 11
Under the hood: fat pointers and unsized types
This chapter assumes you know how to create slices with ranges, pass &[T] and &str to functions, and apply the basic borrowing rules. Here you will see what a slice reference looks like in memory and why the compiler treats [T] differently from [T; N].
Thin and fat pointers
A reference to a sized value, such as &i32, holds one machine address. A slice reference holds two values: the address of the first element and the number of elements. A pointer that carries extra information like this is called a fat pointer.
The slice does not copy elements. Taking &a[1..4] builds a pointer to element 1 and a length of 3. You can check the sizes yourself:
use std::mem::size_of;
fn main() {
println!("&i32 = {}", size_of::<&i32>());
println!("&[i32] = {}", size_of::<&[i32]>());
println!("&str = {}", size_of::<&str>());
println!("Box<[i32]> = {}", size_of::<Box<[i32]>>());
println!("Vec<i32> = {}", size_of::<Vec<i32>>());
}On a 64-bit target this prints 8, 16, 16, 16, and 24. A Vec<i32> needs a third word for its capacity. A Box<[i32]> has no spare capacity, so it needs only a pointer and a length.
Unsized types
The type [i32], without a reference, is a dynamically sized type (DST). Its length is not part of the type, so the compiler cannot know its size at compile time. By contrast, [i32; 5] has the length in its type, so its size is always 20 bytes.
Rust expresses this with the Sized marker trait. Almost every type is Sized, and the compiler assumes it for every generic parameter by default. Because [T] and str are not Sized, you cannot:
- store one in a local variable, such as
let x: [i32] = ... - pass one by value to a function
- return one by value
The compiler reports these as "the size for values of type [i32] cannot be known at compilation time". You always use an unsized type behind a pointer: &[T], &mut [T], Box<[T]>, Rc<[T]>, &str.
The fat pointer supplies the missing information. For a slice, the extra word is the element count. size_of_val combines it with the element size:
use std::mem::size_of_val;
fn main() {
let a = [1u32, 2, 3, 4, 5];
let s: &[u32] = &a[1..4];
println!("len = {}", s.len());
println!("bytes = {}", size_of_val(s));
assert!(std::ptr::eq(s.as_ptr(), &a[1]));
}This prints len = 3 and bytes = 12. The assertion confirms the slice points at the original storage.
Other fat pointers
Slices are not the only case. The extra word depends on the unsized type:
| Reference type | First word | Second word |
|---|---|---|
| `&[T]` | address of first element | element count |
| `&str` | address of first byte | byte count |
| `&dyn Trait` | address of the value | address of the vtable |
| `&T` where `T: Sized` | address of the value | none |
A vtable is a table of function pointers that the compiler builds for each type and trait pair. It is how a trait object finds the right method at run time.
Writing generic code over unsized types
A generic function accepts only sized types unless you opt out with ?Sized:
use std::fmt::Debug;
fn show<T: Debug + ?Sized>(value: &T) {
println!("{:?}", value);
}
fn main() {
show("text");
show(&[1, 2, 3][..]);
show(&5);
}Without ?Sized, the first two calls would not compile. The parameter is a reference, so T can be unsized as long as the pointer carries the extra data.
Common mistakes
- Expecting
&[T]to be the size of&T. It is two words, which matters when you store many slice references in a struct. - Confusing
&[T; N]with&[T]. The first is a thin pointer becauseNis in the type. The second carries its length at run time. Rust converts the first to the second automatically (an unsizing coercion), but never the reverse withouttry_into. - Trying to own a bare
stror[T]. UseBox<str>,Box<[T]>,String, orVec<T>.
Exercise
On a 64-bit target, what are size_of::<&[u8]>() and size_of::<&[u8; 4]>(), and why do they differ?
Show answer
&[u8] is 16 bytes because it is a fat pointer holding an address and a length. &[u8; 4] is 8 bytes because the length 4 is part of the type, so only the address needs to be stored.
Exercise
Why does fn show<T: Debug>(value: &T) reject a &str argument, and what is the fix?
Show answer
A &str argument makes T equal to str, which is unsized, but generic parameters are Sized by default. Writing T: Debug + ?Sized removes that requirement.