Layout and Representation in Rust
In this post
- A struct is a byte budget
- The default layout is an optimization, not a promise
#[repr(C)]: the order becomes yours#[repr(packed)]and#[repr(align(n))]- Enums: a tag plus the largest payload
- Niches: when
Optionis free - What to rely on
A struct is a byte budget
A device reports readings with a status flag and a sensor kind. A natural Rust type puts the fields in the order the problem suggests them:
struct Sample {
active: bool, // 1 byte
reading: u32, // 4 bytes
kind: u8, // 1 byte
}
The comments add up to six bytes. The earlier post on modeling data with Rust’s type system warned against assuming that arithmetic holds, because the default representation leaves the compiler free to rearrange things; this post walks the mechanics behind that warning. It measures what this struct actually costs, explains why the number differs from the field sizes, and separates the parts of the answer that are promises from the parts that are observations.
The default layout is an optimization, not a promise
Rust’s default representation — the reference calls it repr(Rust) — makes three promises, all required for the program to be sound: each field starts at a byte offset that the field’s alignment divides, the type’s alignment is at least the largest of its fields’ alignments, and the fields of a struct do not overlap. Everything else is up to the compiler. The reference says it directly: “Type layout can be changed with each compilation. Instead of trying to document exactly what is done, we only document what is guaranteed today.”
What the compiler does with that freedom is visible. std::mem::offset_of!, stable since Rust 1.77, reports where each field landed:
use std::mem::{offset_of, size_of};
fn main() {
println!("size {}", size_of::<Sample>());
println!("kind at offset {}", offset_of!(Sample, kind));
println!("reading at offset {}", offset_of!(Sample, reading));
println!("active at offset {}", offset_of!(Sample, active));
}
size 8
kind at offset 4
reading at offset 0
active at offset 5
The compiler moved reading to the front. Laying the fields out in declaration order would produce active at 0, then three padding bytes, reading at 4, kind at 8, and three padding bytes to round the whole struct up to its alignment of 4 — twelve bytes, six of them padding. By sorting fields so that the largest alignment comes first, the same struct fits in eight bytes with two padding bytes at the end (reading fills bytes 0–3, kind and active occupy bytes 4 and 5, and two bytes remain before the total reaches the next multiple of 4). Reordering to shrink padding is the kind of change the compiler is allowed to make, and this build made it. A different compiler version may lay the struct out differently — still sound, still eight bytes here, but with no obligation to keep these offsets.
Two habits follow. First, measure instead of adding bytes on paper: size_of and offset_of report the truth for the compiler you ship with. Second, treat the numbers as observations. The overview post made this caution about relying on a layout seen in one compiler version; offset_of turns that caution into a testable check instead of a guess.
#[repr(C)]: the order becomes yours
#[repr(C)] trades that freedom away. The fields are laid out in declaration order, each aligned to its own alignment, with padding inserted where a field needs it:
#[repr(C)]
struct Sample {
active: bool, // offset 0
reading: u32, // offset 4 — 3 bytes of padding came first
kind: u8, // offset 8
} // size 12: 3 bytes of padding close the struct
This is the layout C compilers produce, which is why the attribute exists: data shared with foreign code needs a layout both sides agree on. The cost of the guarantee is visible in the numbers. The same three fields, declared in a different order:
#[repr(C)]
struct Sample {
reading: u32, // offset 0
active: bool, // offset 4
kind: u8, // offset 5
} // size 8
Eight bytes instead of twelve — a third smaller — with no compiler cleverness, just an author who put the u32 first. Under repr(Rust) that optimization is the compiler’s job; under repr(C) it is yours, and the compiler will happily allocate your padding forever.
The declaration order of a repr(C) struct is also load-bearing in another sense: it is part of the type’s contract. Cargo’s semver reference lists reordering the public fields of a repr(C) type as a major change — the public API post made the general point that published surfaces are promises; here the promise extends to byte offsets, because foreign code and binary formats may depend on them. If the layout is not part of a contract, default repr(Rust) is the cheaper choice: it gives the same struct in eight bytes and keeps the right to rearrange.
#[repr(packed)] and #[repr(align(n))]
Two modifiers move alignment down or up.
#[repr(packed)] removes padding entirely:
#[repr(packed)]
struct Sample {
active: bool,
reading: u32,
kind: u8,
}
Six bytes, alignment 1 — the byte budget the original comments suggested, finally true. The price is that reading now starts at offset 1, which no u32 is required to tolerate. Reading the field through a reference would create a misaligned reference, undefined behavior even if the reference is never dereferenced, and the compiler rejects it outright:
error[E0793]: reference to field of packed struct is unaligned
|
| let r = &sample.reading;
| ^^^^^^^^^^^^^^^
|
= note: this struct is 1-byte aligned, but the type of this field may require higher alignment
= note: creating a misaligned reference is undefined behavior (even if that reference is never dereferenced)
= help: copy the field contents to a local variable, or replace the reference with a raw pointer
and use `read_unaligned`/`write_unaligned`
The help line states the safe pattern: copy the field into a local variable first. Packed structs earn their bytes only where a wire or hardware format dictates them, and code that touches them should treat every field read as a copy, not a borrow.
#[repr(align(n))] raises the alignment instead:
#[repr(align(8))]
struct Flags {
on: bool,
off: bool,
}
A plain two-bool struct is two bytes with alignment 1; this one reports alignment 8 and size 8 — the compiler pads it up so that every Flags sits on an 8-byte boundary. Combined with repr(C), the alignment applies on top of the fixed order:
#[repr(C, align(8))]
struct Sample {
active: bool, // offset 0
reading: u32, // offset 4
kind: u8, // offset 8
} // size 16: rounded up to the next multiple of 8
Sixteen bytes for six bytes of data. Raising alignment is for cases that genuinely need it — SIMD loads, cache-line isolation, DMA buffers — and the cost shows up in every array of the type, since each element occupies a full stride.
Enums: a tag plus the largest payload
An enum stores which variant applies, plus the largest variant’s data. The machinery mirrors structs:
enum Kind {
Temp,
Pressure,
Humidity,
}
enum Reading {
Offline,
Live(f64),
}
A field-less enum like Kind needs only its discriminant — this build gives it one byte, with variants numbered from zero. Reading carries an f64, so it is one tag byte plus eight payload bytes plus padding to keep the f64 aligned: sixteen bytes total, eight of them payload, with the tag and its padding taking the other half. The tag is small; the stride is set by the widest variant, so one heavyweight variant taxes every value of the enum, the same way the aligned struct’s stride taxed every element of its array.
The default discriminant is a compiler decision, and code that hands an enum to C or writes it to a binary format needs a fixed one. #[repr(u8)] makes the one byte and the numbering part of the contract; #[repr(C)] gives the C-compatible shape — a C int-sized discriminant, four bytes here, even for a field-less enum. The reference describes a repr(C) enum with fields as “a repr(C) struct with two fields, also called a ‘tagged union’ in C” — tag and payload laid out like any other struct, with the same padding rules and the same author responsibility for them.
Niches: when Option is free
Option<T> must record whether a value is present, which sounds like it needs the tag byte that Reading needs. It often does not. A type whose set of valid bit patterns does not fill its storage has spare patterns — niches — and the compiler can store the discriminant in one of them instead of in new bytes. A reference cannot be null, so Option<&Sample> writes None into the pattern that &Sample can never legally hold:
use std::mem::size_of;
fn main() {
println!("{}", size_of::<&Sample>()); // 8
println!("{}", size_of::<Option<&Sample>>()); // 8
}
Eight bytes either way: the Option costs nothing. Which types get this treatment is documented, and worth reading precisely — the Option representation section guarantees the same size, alignment, and function-call ABI for references, Box, function pointers, NonZero* integers, NonNull, and #[repr(transparent)] wrappers around those. The transparent-wrapper clause extends a rule the typestate post relied on: a PhantomData field adds no storage, so an Order<Draft> occupies exactly its payload bytes. #[repr(transparent)] turns that observation into a published guarantee — a transparent wrapper around a non-zero integer keeps the integer’s size and can hand its Option to foreign code with that guarantee attached.
Everything outside that list is an observation for the compiler you have, not a promise. Measured on the same build, on a 64-bit target:
Option<NonZeroU32> 4 documented
Option<&Sample> 8 documented
Option<u32> 8 no niche exists — u32 has no invalid patterns
Option<bool> 1 observed: 254 invalid encodings supply the niche
Option<Kind> 1 observed: the discriminant has spare values
Option<Sample> 8 observed: the bool field supplies a niche
The last line is the generalization worth internalizing: niches are recursive. Sample is Option-free at eight bytes because its own active: bool leaves an invalid encoding the compiler can use. Option<u32> pays full price because a u32 has no spare patterns at all. The Option-vs-Result post covered what Option means; this is what it costs, and the two questions have different answers — the meaning is guaranteed, the cost is mostly inference the compiler may or may not perform.
What to rely on
The layout tools separate cleanly into measurements and promises. size_of, align_of, and offset_of measure the compiler you have; repr attributes promise a layout to the compiler you will have and to foreign code; the reference and the Option documentation list the guarantees that hold without any attribute. Code that ships bytes — FFI, file formats, network protocols, shared memory — should specify a representation and test it; code that moves values inside one process usually gets the default representation’s reordering for free.
A sensible order of operations for a type that will outlive this year’s compiler: write the fields in whatever order reads best, let repr(Rust) compact them, and reach for #[repr(C)] only when a boundary needs the order — taking on the padding arithmetic and the semver responsibility that come with it. The attributes are cheap to add and expensive to remove, and that asymmetry, not the byte count, is the real design decision.