Memory Layout

1

Structs and Memory Layout

6 minute

C developers often read struct as a memory layout:

#include <stdint.h>

struct Header {
    uint8_t version;
    uint32_t length;
    uint16_t flags;
};

Fields are laid out in declaration order, padding may be inserted, and the whole struct has an alignment requirement. That mental model matters for protocols, file formats, register maps, and FFI.

Rust also has struct, but the first split is this:

normal Rust struct: describes an internal data model
#[repr(C)] struct: describes a layout that must match the C ABI

The keyword is familiar, but the default layout contract is not the same. In ordinary Rust code, treat a struct as named fields. Bring memory layout into the type only when an ABI or binary boundary needs it.

Read More