Why size and alignment matter

Every Rust value occupies some number of bytes and has an alignment requirement. The size tells you how much memory a value consumes; the alignment tells you where it may legally start in memory.

These properties matter when you:

  • interoperate with C APIs and binary protocols
  • allocate raw buffers for typed data
  • optimize memory footprint in large collections
  • write unsafe code that casts pointers or builds values in place
  • reason about cache locality and padding

A common mistake is to treat “size” as the only relevant property. In reality, alignment can force padding between fields or at the end of a struct, making the actual memory footprint larger than the sum of the field sizes.


The basic APIs

Rust exposes two core functions:

use std::mem::{align_of, size_of};

fn main() {
    println!("u8: size={}, align={}", size_of::<u8>(), align_of::<u8>());
    println!("u32: size={}, align={}", size_of::<u32>(), align_of::<u32>());
    println!("f64: size={}, align={}", size_of::<f64>(), align_of::<f64>());
}

These functions are compile-time constants for a given type. In practice, that means they are cheap to use in constant expressions, array lengths, and layout assertions.

Key rules

  • size_of::<T>() returns the number of bytes occupied by a value of type T.
  • align_of::<T>() returns the required alignment in bytes for T.
  • A type’s alignment is always a power of two.
  • The size of a type is always a multiple of its alignment, except for zero-sized types.

A quick mental model of layout

Consider this struct:

#[repr(C)]
struct Packet {
    version: u8,
    length: u32,
    flags: u16,
}

You might expect 1 + 4 + 2 = 7 bytes. In reality, the compiler inserts padding to satisfy alignment requirements. On many platforms, u32 wants 4-byte alignment, so length may start at offset 4 rather than 1.

A more realistic layout could be:

  • version: 1 byte
  • padding: 3 bytes
  • length: 4 bytes
  • flags: 2 bytes
  • padding: 2 bytes

Total: 12 bytes

The exact result depends on the target architecture and representation attributes, but the principle is universal: field order affects padding.


Inspecting layout in practice

You can print sizes and alignments to understand your data structures:

use std::mem::{align_of, size_of};

#[repr(C)]
struct Packet {
    version: u8,
    length: u32,
    flags: u16,
}

fn main() {
    println!("Packet size: {}", size_of::<Packet>());
    println!("Packet align: {}", align_of::<Packet>());
    println!("u8 size: {}", size_of::<u8>());
    println!("u32 align: {}", align_of::<u32>());
}

This is useful when debugging protocol mismatches or verifying assumptions before writing unsafe code.

Comparing common types

TypeTypical sizeTypical alignmentNotes
u811No padding required
u1622Often used in packed binary formats
u3244Common alignment boundary
u6488Useful for timestamps and pointers on 64-bit targets
bool11Rust guarantees valid values are true or false
char44Unicode scalar value, not a byte

These values are typical, but you should always query them rather than assuming them in portable code.


FFI: matching C layouts safely

When calling C or exposing Rust types to C, layout compatibility is critical. Rust’s default struct layout is intentionally unspecified, so you should use #[repr(C)] for FFI-facing types.

#[repr(C)]
pub struct CPoint {
    pub x: f32,
    pub y: f32,
}

With repr(C), Rust arranges fields in the same order and with the same general alignment rules as C. This makes it suitable for passing structs across language boundaries.

Best practices for FFI layout

  • Use #[repr(C)] for structs shared with C.
  • Avoid Rust-specific types like String, Vec<T>, or Option<&T> in FFI structs unless you fully control both sides and understand their ABI.
  • Prefer fixed-width integer types such as u32 and i64.
  • Verify layout with size_of and align_of during development.
  • Be careful with #[repr(packed)]; it can create unaligned fields and make safe field access impossible.

Example: validating a C-compatible struct

use std::mem::{align_of, size_of};

#[repr(C)]
struct Header {
    magic: u32,
    version: u16,
    flags: u16,
}

const _: () = {
    assert!(size_of::<Header>() == 8);
    assert!(align_of::<Header>() == 4);
};

This pattern is valuable in build-time checks and test suites. If a future change alters the layout, the assertion fails immediately.


Field order and padding optimization

If you control a struct’s design, you can often reduce memory usage by ordering fields from largest alignment to smallest.

Poorly ordered

struct A {
    a: u8,
    b: u64,
    c: u16,
}

Better ordered

struct B {
    b: u64,
    c: u16,
    a: u8,
}

The second version often uses less padding because the largest-alignment field comes first. This matters in large arrays, where wasted bytes multiply quickly.

When optimization is worth it

Reordering fields is most useful when:

  • the type appears in large collections
  • the type is copied frequently
  • memory bandwidth is a bottleneck
  • you are designing a wire format or storage format

It is less important for small, infrequently used types where readability matters more than a few bytes of padding.


Zero-sized types and PhantomData

Not every type consumes storage. Zero-sized types (ZSTs) have size_of::<T>() == 0. They are often used to encode compile-time information without runtime cost.

use std::marker::PhantomData;
use std::mem::size_of;

struct Wrapper<T> {
    _marker: PhantomData<T>,
}

fn main() {
    println!("{}", size_of::<Wrapper<u32>>());
}

PhantomData<T> is a zero-sized marker that tells the compiler about ownership, variance, and drop semantics. It is common in advanced abstractions, especially when a type logically depends on T but does not store a T directly.

Why this matters

Zero-sized types can appear in generic APIs, iterators, and marker-based designs. Even though they occupy no space, they still participate in type checking and trait resolution. That makes them powerful for encoding intent without runtime overhead.


Alignment and unsafe pointer casts

If you are working with raw pointers, alignment is not optional. A pointer to bytes is not automatically valid for any type.

use std::mem::align_of;

fn is_aligned<T>(ptr: *const u8) -> bool {
    (ptr as usize) % align_of::<T>() == 0
}

Before casting a const u8 to const T, ensure the address satisfies T’s alignment. Failing to do so can cause undefined behavior, even if the bytes “look correct.”

Common unsafe pattern

fn read_u32(buf: &[u8]) -> Option<u32> {
    if buf.len() < 4 {
        return None;
    }

    let ptr = buf.as_ptr();
    if (ptr as usize) % std::mem::align_of::<u32>() != 0 {
        return None;
    }

    unsafe { Some(*(ptr as *const u32)) }
}

This example is intentionally conservative. In production code, prefer safe parsing methods such as from_le_bytes or from_ne_bytes unless you truly need raw-pointer access.


repr(C) is not a magic shield

Using #[repr(C)] improves predictability, but it does not make every operation safe. You still need to respect:

  • alignment requirements
  • valid bit patterns
  • endianness
  • padding bytes
  • ownership and lifetimes

For example, a repr(C) struct containing a bool still requires valid boolean values. A repr(C) enum may still have platform-dependent ABI details unless carefully designed. Layout compatibility is only one piece of correctness.


Practical guidelines for developers

Use size_of and align_of as part of a broader layout strategy:

  1. Measure before optimizing. Don’t assume a struct is “small enough.”
  2. Use repr(C) for FFI. Never rely on default Rust layout across language boundaries.
  3. Prefer field reordering over packed structs. Packed structs can introduce unsafe unaligned access.
  4. Assert critical layouts. Build-time or test-time checks catch regressions early.
  5. Treat alignment as a safety constraint. It is not just a performance detail.
  6. Use safe byte conversion APIs when possible. Raw casting should be the exception, not the default.

Summary

std::mem::size_of and std::mem::align_of are foundational tools for low-level Rust development. They help you understand how values are laid out in memory, which is essential for FFI, buffer handling, and unsafe code. By combining these APIs with #[repr(C)], careful field ordering, and explicit layout checks, you can write code that is both efficient and predictable.

The key takeaway is simple: in advanced Rust, memory layout is part of your API contract. Know it, verify it, and design with it in mind.

Learn more with useful resources