Skip to content
Tutorials Center
My learning

Topics

Lesson 70 of 132 ยท Smart Pointers and Memory

Memory Layout and Sizes

See how Rust lays values out in memory: size_of and align_of, padding, field reordering, repr(C), niche optimization, stack versus heap, and zero-sized types.

Most of the time you never think about how many bytes a value takes. Rust is a systems language, though, and sooner or later you will want to know: how big is this struct, why is my enum larger than I expected, and what does Option<Box<T>> cost? The answers are not magic. They follow a few simple rules about size, alignment and padding, and the compiler gives you tools (size_of, align_of, #[repr]) to look at them.

This lesson shows you how to measure a type, why the compiler adds invisible padding, how Rust is free to reorder your fields, how repr(C) takes that freedom away, and how the compiler squeezes enums into fewer bytes with niche optimization. It builds on Smart Pointers Overview and Drop and RAII, and prepares you for Unsafe Rust and FFI.

All sizes in this lesson are for a typical 64-bit platform (pointers are 8 bytes). Rust only guarantees a few of them (for example size_of::<u32>() == 4); the rest are what the current compiler does, so treat them as facts to understand, not to depend on.

Measuring with size_of and align_of

std::mem::size_of::<T>() returns the number of bytes a value of type T occupies. std::mem::align_of::<T>() returns its alignment: the address of a T must be a multiple of that number. Both are computed at compile time and are const fns.

Rust Sizes and alignments of basic types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Two facts to take away. First, a char is 4 bytes because it holds any Unicode scalar value, not a byte. Second, the size of a tuple or struct is not simply the sum of its fields: (u8, u32) is 8 bytes, not 5. The extra bytes are padding.

Since Rust 1.80, size_of and align_of are also in the prelude, so in the 2024 edition you can call size_of::<T>() without importing anything. We import them here to make the origin obvious.

Alignment and padding

CPUs read memory fastest (and on some hardware, only) when a value sits at an address that is a multiple of its size. A u32 wants an address divisible by 4, a u64 by 8. To guarantee that, the compiler:

  1. gives each type an alignment (usually equal to its size, up to the pointer size),
  2. inserts padding bytes between fields when needed, and
  3. rounds the total size up to a multiple of the struct's alignment, so that an array of the struct keeps every element aligned.

Here is a struct laid out by hand, field after field, in the order written. That is exactly what #[repr(C)] does, and it makes the padding easy to see:

TEXT
#[repr(C)] struct Sample { a: u8, b: u32, c: u8 }

offset: 0    1  2  3   4  5  6  7   8    9 10 11
        [a ] [pad pad pad] [b  b  b  b] [c] [pad pad pad]
        size = 12, alignment = 4

a takes one byte. b needs an address divisible by 4, so three bytes of padding follow. c takes one byte at offset 8, and three more bytes of tail padding bring the total to 12, a multiple of 4. Only 6 of 12 bytes carry data.

Rust Padding in a repr(C) struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The offset_of! macro (stable since Rust 1.77) reports where a field starts inside the struct. It works for any struct, and it is the right tool when you need to know a layout without doing the arithmetic yourself.

Rust reorders your fields

Here is the surprise for anyone coming from C. With Rust's default representation, #[repr(Rust)], the compiler is allowed to put fields in any order it likes. Almost always it sorts them to waste as little space as possible, usually from largest alignment to smallest. Same struct, no attribute:

Rust The default representation reorders fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The default version needs only 8 bytes (b, then a and c side by side, no inner padding). The repr(C) version needs 12. Same fields, 50% bigger, purely because of order.

The practical consequences:

  • You rarely need to reorder fields by hand. The compiler does it for you. Declare fields in the order that reads best.
  • You cannot rely on the order of fields in memory unless you ask for it with repr(C). Casting a pointer to a Rust struct into bytes and expecting a particular layout is a bug.
  • Two structs with the same fields in a different order may have identical sizes.

The representation attributes

#[repr(...)] tells the compiler which layout rules to follow.

Attribute Meaning
#[repr(Rust)] The default. Reordering allowed, layout unspecified.
#[repr(C)] Fields in declaration order, C padding rules. Needed for FFI.
#[repr(transparent)] A struct with one non-zero-sized field has exactly that field's layout and ABI.
#[repr(u8)], #[repr(i32)], ... On an enum: use that integer type as the discriminant.
#[repr(packed)] Remove padding (alignment 1). References to fields can become invalid; use with great care.
#[repr(align(N))] Raise the alignment to at least N bytes (for example cache-line alignment).

repr(transparent) is the layout guarantee behind the newtype pattern: wrapping a u32 in struct UserId(u32) costs nothing, and with repr(transparent) you may pass a UserId to C code expecting a u32.

Rust repr(transparent), repr(u8) and repr(align)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

repr(align(64)) pads the struct out to 64 bytes. That is useful when several threads each update their own counter: placing counters on separate cache lines avoids false sharing, where unrelated variables on the same line slow each other down.

Enums: a tag plus the largest variant

A Rust enum can hold different data in each variant, so it has to remember which variant is active. The compiler stores a tag (the discriminant) plus enough space for the largest variant, then rounds up for alignment.

Rust How big is an enum?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

A fieldless enum like Color needs only one byte for the tag. Shape carries up to two f64 values (16 bytes) plus a tag, padded to 8-byte alignment: 24 bytes. And Option<u32> is 8 bytes, not 5: one byte of tag, three of padding, four of value. This explains a classic performance tip: one big variant makes every value of the enum big. If a rare variant holds a 1 KB array, every Vec element of that enum pays for 1 KB. Box the large payload to keep the enum small.

Niche optimization: free Options

Now the clever part. Some types have bit patterns that can never occur in a valid value: a reference is never null, a bool is only 0 or 1, a char is never above 0x10FFFF. These unused patterns are called niches. The compiler can use a niche to encode "no value", so no separate tag is needed.

Rust Niche optimization in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Option<&u8>, Option<Box<u64>> and Option<String> are the same size as the type inside: the null pointer (and a niche in the capacity field of String) stands for None. Option<bool> fits in one byte, using value 2 for None. A plain u32 has no spare patterns, so Option<u32> grows to 8, but NonZeroU32 promises "never zero", and that gives the compiler its niche back.

This is why "nullable pointers" in Rust are safe and free: Option<&T> compiles to the same machine code as a C pointer that may be null, but the type system forces you to check it. See Option.

The compiler makes no promise that a given niche is used in every case (the rules have gotten smarter over releases), so verify with size_of if the size matters to you.

Stack and heap, and what a pointer type contains

Where a value lives is separate from how big it is.

  • Stack: local variables, function arguments, and values like integers, arrays and structs. Allocation is just moving a pointer; the memory is released automatically when the function returns. Sizes must be known at compile time.
  • Heap: memory requested at run time, for data whose size is dynamic or that must outlive the current function. Box, Vec, String and Rc allocate there. Allocation is slower (a call to the allocator) and requires freeing.

The handles are small and stack-allocated; the data they own is on the heap:

Rust Handles are small, data can be huge

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

A &str and a slice reference are fat pointers: a data pointer plus a length. A &dyn Trait is a data pointer plus a vtable pointer (see Trait Objects). A Vec is three words: pointer, capacity, length. size_of_val measures a value you already have, which also works on unsized things like slices: size_of_val(&big[..]) would report one million.

Zero-sized types

Some types occupy zero bytes: the unit type (), an empty struct, an empty array, PhantomData<T>, and fieldless enums with one variant. They carry information only in the type system.

Rust Zero-sized types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Zero-sized types are not a curiosity. HashSet<T> is implemented as HashMap<T, ()>, and the () costs nothing. Type-state builders (Type-State and Builders) use zero-sized marker types to make invalid states unrepresentable at no run-time cost. Result<(), E> stores just the error plus a tag.

Seeing the real layout

When you are curious how the compiler arranged something, print what you can measure: size_of, align_of, offset_of!. In a full project you can ask the compiler directly: cargo rustc -- -Zprint-type-sizes on a nightly toolchain prints every type's layout. Our editor only runs single files with stable Rust, so we stick to the stable tools above.

Terminal
# Read-only: needs a nightly toolchain and a Cargo project
cargo +nightly rustc -- -Zprint-type-sizes

When a hot loop is slow, check the size of what it iterates over. Shrinking a struct from 64 to 32 bytes (smaller integers, Boxing a rare big variant, or reordering for repr(C)) halves the cache lines touched. Measure before and after; do not guess.

Common mistakes

  • Assuming declaration order is memory order. With the default repr, it is not. Use repr(C) when order matters.
  • Using repr(packed) and taking references. A reference to a misaligned field is undefined behavior; the compiler rejects most such references, but copying the field by value is the safe way.
  • Printing sizes and treating them as portable. usize and pointers change with the platform (4 bytes on 32-bit targets).
  • Making an enum huge for one rare variant. Box that variant's payload.
  • Forgetting Option<Box<T>> is free but Option<T> is not. For ordinary integers, Option adds a tag and padding.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the size of (u8, u32) on a typical 64-bit platform?

    The u32 needs 4-byte alignment, so the u8 is followed by 3 bytes of padding. 1 + 3 + 4 = 8, which is also a multiple of the tuple's alignment (4).
  2. 2. Why can a struct declared as { a: u8, b: u32, c: u8 } be smaller with the default representation than with #[repr(C)]?

    Only repr(C) fixes the field order to the declaration order. With the default repr, Rust may place the u32 first and the two u8 values after it, giving 8 bytes instead of 12.
  3. 3. Why is Option<Box<u64>> the same size as Box<u64>?

    A valid Box is never null. The compiler uses the unused all-zero pointer pattern to represent None, so no extra tag byte is needed. Option<u32> has no such unused pattern and is larger than u32.
  4. 4. What does size_of::<PhantomData<String>>() return?

    PhantomData is a zero-sized type. It exists only for the type checker, for example to tie a generic parameter to a struct without storing a value.
  5. 5. Which attribute guarantees that a newtype struct Id(u32) has exactly the layout and ABI of a u32?

    repr(transparent) says the wrapper has the same layout as its single non-zero-sized field, which matters when passing the value to C code.

Summary

  • size_of::<T>() and align_of::<T>() measure any sized type at compile time; size_of_val measures a value you hold, including slices.
  • Padding keeps fields aligned and rounds a struct's size up to a multiple of its alignment.
  • The default repr(Rust) may reorder fields to save space; repr(C) keeps declaration order and C rules; repr(transparent), repr(u8), repr(align(N)) and repr(packed) cover special cases.
  • An enum is a tag plus its largest variant; niches (null pointers, bool, NonZero*) let Option take no extra space.
  • Box, Vec and String are small stack handles to heap data; &str, slices and &dyn Trait are fat pointers.
  • Zero-sized types cost nothing and carry meaning in the type system.

Next: Cow, Borrow and Avoiding Clones