Layout guarantees and niche optimizations
Quick answer
A type's memory layout includes size and alignment. Some types have invalid bit patterns that Rust can use to encode enum variants without additional storage, a technique called niche optimization.
Distinguish guarantee from observation
Default Rust representation does not guarantee field order. repr(C) gives documented C-style layout rules for structs but not a portable wire format. Option<NonZeroU32> is guaranteed to have the size and alignment of NonZeroU32, since zero can encode None. Do not generalize that guarantee to every Option<T>.
use std::{mem::{size_of, align_of}, num::NonZeroU32};fn main() { println!("{} {}", size_of::<Option<NonZeroU32>>() == size_of::<NonZeroU32>(), align_of::<Option<NonZeroU32>>() == align_of::<NonZeroU32>());}Expected stdout (not executed):
true trueThe documented guarantee is stronger than an observed size on one machine.
#[repr(C)] struct Pair { a: u8, b: u32 }fn main() { println!("{}", std::mem::size_of::<Pair>() % std::mem::align_of::<Pair>() == 0); }Expected stdout (not executed):
truePadding and alignment matter; actual values can depend on the target.
Common mistake
Never treat raw struct memory as a stable serialized format.
Try it yourself
Compare size_of for u32, Option<u32> and Option<NonZeroU32>; identify which equality is guaranteed.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Layout guarantees and niche optimizations — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
Can the default layout of a Rust struct be used as a portable network byte format?
Layout guarantees and niche optimizations — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::{mem::{size_of, align_of}, num::NonZeroU32}; fn main() { println!("{} {}", size_of::<Option<NonZeroU32>>() == size_of::<NonZeroU32>(), align_of::<Option<NonZeroU32>>() == align_of::<NonZeroU32>()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Layout guarantees and niche optimizations — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust #[repr(C)] struct Pair { a: u8, b: u32 } fn main() { println!("{}", std::mem::size_of::<Pair>() % std::mem::align_of::<Pair>() == 0); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.