Sub topic 2
Zero-sized types: types that take no space
This chapter assumes you know Rust structs, enums, generics with trait bounds, and how to run cargo run and read compiler output. It covers the zero-sized types (ZSTs) that the rest of the tutorial builds on. Marker types and PhantomData both depend on them.
What a zero-sized type is
A zero-sized type is a type whose values occupy no bytes. std::mem::size_of::<T>() returns 0 for it. A value of such a type still exists as far as the type checker is concerned. You can create it, move it, pass it to functions and match on it. At runtime, none of that touches memory.
Rust has several kinds of ZST:
| Type | Example | Why its size is 0 | Column | Column |
|---|---|---|---|---|
| Unit type | `()` | It has exactly one value, so no data is needed to tell values apart. | ||
| Unit struct | `struct Marker;` | One value, no fields. | ||
| Empty struct | `struct E {}` or `struct T();` | No fields. | ||
| Struct of ZSTs | `struct N(Marker, ());` | The sum of the field sizes is 0. | ||
| Zero-length array | `[u64; 0]` | There are no elements. | ||
| Single-variant enum | `enum Only { A }` | One possible value. | ||
| Empty enum | `enum Never {}` | No possible values, so none can be built. | ||
| Function item | `main` | The type identifies the function, so no pointer is stored. | ||
| Non-capturing closure | `\ | \ | 42` | Nothing is captured. |
The rule behind the table is that a type needs storage only to tell its possible values apart. A type with zero or one possible value needs no bits.
Measuring sizes
The program below prints the size of each case. Run it to check the table.
use std::mem::{align_of, size_of, size_of_val};
#[allow(dead_code)]
struct Unit;
struct Braces {}
struct Tuple();
#[allow(dead_code)]
struct Nested(Unit, (), [u8; 0]);
#[allow(dead_code)]
struct Tagged {
id: u64,
tag: Unit,
}
#[allow(dead_code)]
enum Single {
Only,
}
#[allow(dead_code)]
enum Two {
A,
B,
}
enum Never {}
#[allow(dead_code)]
struct Padded {
a: u8,
zero: [u64; 0],
}
fn main() {
println!("() = {}", size_of::<()>());
println!("Unit = {}", size_of::<Unit>());
println!("Braces = {}", size_of::<Braces>());
println!("Tuple = {}", size_of::<Tuple>());
println!("Nested = {}", size_of::<Nested>());
println!("Tagged = {}", size_of::<Tagged>());
println!("Single = {}", size_of::<Single>());
println!("Two = {}", size_of::<Two>());
println!("Never = {}", size_of::<Never>());
println!("Padded = {} (align {})", size_of::<Padded>(), align_of::<Padded>());
let closure = || 42;
let n = 5i32;
let capturing = move || n;
println!("closure = {}", size_of_val(&closure));
println!("capturing closure = {}", size_of_val(&capturing));
println!("fn item = {}", size_of_val(&main));
println!("fn pointer = {}", size_of::<fn()>());
let v = vec![(); 1_000_000];
println!("Vec<()> len = {}, bytes = {}", v.len(), size_of_val(v.as_slice()));
}On a 64-bit platform the output is:
() = 0
Unit = 0
Braces = 0
Tuple = 0
Nested = 0
Tagged = 8
Single = 0
Two = 1
Never = 0
Padded = 8 (align 8)
closure = 0
capturing closure = 4
fn item = 0
fn pointer = 8
Vec<()> len = 1000000, bytes = 0Several lines are worth a closer look:
Taggedis 8 bytes. TheUnitfield adds nothing to theu64.Twois 1 byte. Two values need one bit of information, and the smallest unit of storage is a byte.- The capturing closure is 4 bytes because it stores a copy of
n. Capturing is what costs space. - The fn item
mainis 0 bytes, butfn()is 8 bytes. The fn item type names one specific function. The fn pointer type can point at any function with that signature, so it must store an address. - A
Vec<()>with a million elements holds no element data. Collections handle ZSTs without allocating per element.Vec<()>reports a capacity ofusize::MAX.
Alignment can still add space
A ZST has a size of 0, but it can still have an alignment requirement. A zero-length array of u64 has size 0 and alignment 8. Putting it in a struct forces the whole struct to be aligned to 8 bytes, so Padded rounds up from 1 byte to 8. Unit structs and () have alignment 1, so they never cause padding. This matters later, when you choose what to put inside a PhantomData.
What the compiler does with a ZST
Moving, copying and passing a ZST compiles to no instructions. A function that takes a Marker argument takes it in no register. A Vec<Marker> stores only a length.
The standard library uses this in real code. HashSet<T> is a HashMap<T, ()>, so the value half of each entry costs nothing. Result<(), E> uses () for "success with no data". Result<T, Infallible> uses an empty enum to say that an error cannot happen.
References to ZSTs are valid. A &Marker is a non-null, correctly aligned pointer, but it need not point at distinct memory. Two different ZST values can have the same address, so never use a ZST's address as its identity.
Zero size does not mean zero behavior. A ZST that implements Drop still runs its drop code when it goes out of scope, and a unit struct can implement any trait. Types that carry only behavior or identity are the whole point of the pattern in the next sections.
A ZST as a type-level label
Because a unit struct has no data, its only role is its identity as a type. Meters and Feet are different types even though neither holds anything. You can store such a value in a generic struct and let it distinguish otherwise identical data.
use std::mem::size_of;
trait Measure {
const SYMBOL: &'static str;
}
struct Meters;
struct Feet;
impl Measure for Meters {
const SYMBOL: &'static str = "m";
}
impl Measure for Feet {
const SYMBOL: &'static str = "ft";
}
#[allow(dead_code)]
struct Length<U: Measure> {
value: f64,
unit: U,
}
impl<U: Measure> Length<U> {
fn new(value: f64, unit: U) -> Self {
Length { value, unit }
}
fn show(&self) -> String {
format!("{} {}", self.value, U::SYMBOL)
}
}
fn total_meters(a: &Length<Meters>, b: &Length<Meters>) -> f64 {
a.value + b.value
}
fn main() {
let a = Length::new(3.0, Meters);
let b = Length::new(4.5, Meters);
let f = Length::new(10.0, Feet);
println!("{} + {} = {} m", a.show(), b.show(), total_meters(&a, &b));
println!("{}", f.show());
println!("size = {}", size_of::<Length<Meters>>());
// total_meters(&a, &f); // error: expected `Length<Meters>`, found `Length<Feet>`
}It prints:
3 m + 4.5 m = 7.5 m
10 ft
size = 8Three things happen here:
Length<Meters>andLength<Feet>are separate types. Passing a length in feet tototal_metersfails to compile.U::SYMBOLis resolved at compile time from the type parameter. There is no runtime tag to read.Length<Meters>is 8 bytes, the same as a baref64. The label costs nothing.
The limit of this approach
This version stores a real U value in the struct. That works, but it has two costs:
- Every constructor must be given a value of the marker type, as in
Length::new(3.0, Meters). - The marker type must be constructible. You cannot tag a value with an empty enum like
Never, or with a type that has a private constructor or required data.
In many designs the tag is only a label. It should not be a field, and nobody should have to build it. If you remove the unit field and keep the U parameter, the compiler rejects the struct:
struct Length<U> {
value: f64,
}error[E0392]: type parameter `U` is never usedRust requires every type parameter to appear in some field, because it needs to know how the parameter affects variance, drop checking and auto traits. The next chapter resolves this with PhantomData, which is itself a zero-sized type that "uses" a parameter without storing it.
Common mistakes
- Treating
size_of::<T>() == 0as proof that a type is useless. Many standard types rely on it. - Using addresses of ZSTs to compare identity. Distinct ZST values may share an address.
- Putting a zero-length array with large alignment in a struct and being surprised by padding.
- Forgetting that a ZST with a
Dropimplementation still runs code. - Confusing a fn item with a fn pointer. The item is zero-sized and the pointer is not, so storing
fn()in a struct adds 8 bytes.
Exercise
A struct is declared as struct Pair { a: u32, m: Marker, b: u16 }, where Marker is a unit struct. What does size_of::<Pair>() return on a typical 64-bit platform, and how much of it does Marker account for?
Show answer
It returns 8. The fields a (4 bytes) and b (2 bytes) need 6 bytes. The struct's alignment is 4, so the size rounds up to 8. Marker accounts for 0 bytes. Removing the m field would not change the result.
Exercise
Why does size_of::<fn()>() return 8 while size_of_val(&main) returns 0, even though both refer to a function with the same signature?
Show answer
The type of main is a unique function item type that identifies exactly one function, so the compiler knows the target without storing it. A fn() is a pointer that can refer to any function with that signature, so it must store an address, which takes 8 bytes on a 64-bit platform.