Sub topic 2
Zero-sized types: types that take no space
This chapter assumes you know Rust structs, impl blocks and generics, and that you can run cargo run and read compiler errors. The goal is to see that a type can exist, have a name and implement traits while using no memory. The rest of the tutorial builds on that.
What a zero-sized type is
A zero-sized type (ZST) is a type whose values occupy 0 bytes. A value needs storage only to hold information. If a type has exactly one possible value, there is nothing to store, so the compiler stores nothing.
These are all zero-sized:
- The unit type
(). - A unit struct such as
struct Marker;. - A struct with no fields, such as
struct Empty {}. - An array of length zero, such as
[u32; 0]. - A struct or tuple made only of zero-sized fields.
You can check this with std::mem::size_of.
use std::mem::{size_of, size_of_val};
#[derive(Clone, Copy)]
struct Marker;
struct Empty {}
struct Wrapper {
marker: Marker,
count: u32,
}
fn main() {
println!("() = {}", size_of::<()>());
println!("Marker = {}", size_of::<Marker>());
println!("Empty = {}", size_of::<Empty>());
println!("[u32; 0] = {}", size_of::<[u32; 0]>());
println!("Wrapper = {}", size_of::<Wrapper>());
println!("Option<Marker>= {}", size_of::<Option<Marker>>());
let many = vec![Marker; 1000];
println!("len = {}", many.len());
println!("bytes in data = {}", size_of_val(&many[..]));
}Running it prints 0 for (), Marker, Empty and [u32; 0]. Wrapper prints 4, because marker adds nothing to the u32. The vector reports a length of 1000 but its elements take 0 bytes.
Gotcha: wrapping a ZST in an enum
Option<Marker> prints 1, not 0. Option must record whether a value is present, and that record needs a byte. Zero size comes from having exactly one possible value. Option<Marker> has two (None and Some(Marker)), so it is not zero-sized.
Same size, different types
Two zero-sized types have the same size, but the compiler still treats them as unrelated types.
struct Open;
struct Closed;
fn needs_open(_: Open) {}
fn main() {
needs_open(Open);
// needs_open(Closed); // error: expected `Open`, found `Closed`
}The size is 0 for both, yet the call with Closed fails to compile. This is the property the tutorial relies on. Type identity is checked at compile time, and a ZST adds no runtime data to that check.
What ZSTs can do
A zero-sized type is an ordinary type in every other respect:
- It can implement traits, and you can call methods on its values.
- It can be a generic argument, as in
Vec<Marker>orOption<Marker>. - It can derive
Clone,Copy,DebugandPartialEq. - It can be a field of a larger struct without changing that struct's size.
The last point matters most. A struct can hold a ZST field to carry type information at no cost.
use std::mem::size_of;
struct Open;
struct Door {
id: u32,
state: Open,
}
fn main() {
assert_eq!(size_of::<Door>(), size_of::<u32>());
println!("Door is {} bytes", size_of::<Door>());
}Here state records that the door is open, and Door is still only 4 bytes.
The limit that comes next
A zero-sized field is a value, so it must be stored in the struct as a field. The tutorial's goal is different. It needs a type parameter on a struct, such as Door<State>, even when no field uses it. Rust rejects an unused type parameter, which is the problem the next chapters solve with PhantomData. ZSTs are the tags you will plug into that parameter.
Exercise
Given struct Marker;, what does std::mem::size_of::<(Marker, u32)>() return, and why? What would size_of::<Option<Marker>>() return?
Show answer
The tuple is 4 bytes. Marker is zero-sized and adds nothing, so the size is that of the u32. Option<Marker> is 1 byte, because it has two possible values (None and Some(Marker)) and needs a discriminant to tell them apart.