Answer#
Inside a pure Rust program you do not care how a struct is laid out in memory. At a boundary with C, a file format or the network you do: both sides must agree on the order, size and padding of the fields.
By default Rust is free to reorder the fields of a struct to reduce padding, so the layout is not stable. #[repr(C)] fixes the layout to what a C compiler for the same target would produce. The program prints the size and field offsets of the same three-field struct in both forms, compares a C union with a Rust enum, and shows the size of pointer-like types. It was compiled and run with rustc 1.93.0 on a 64-bit Windows target.
use std::mem::{align_of, offset_of, size_of};
// C: struct header { uint8_t kind; uint32_t len; uint16_t flags; };
#[repr(C)]
struct HeaderC {
kind: u8,
len: u32,
flags: u16,
}
// Without repr(C) the compiler may reorder the fields to waste less space.
struct HeaderRust {
kind: u8,
len: u32,
flags: u16,
}
// C: union value { int32_t i; float f; }; used with a separate "which one is it" field
#[repr(C)]
union Value {
i: i32,
f: f32,
}
// Rust: the tag and the data travel together, and match checks the tag.
enum Tagged {
Int(i32),
Float(f32),
}
fn main() {
println!("HeaderC: size {} align {} offsets kind {} len {} flags {}", size_of::<HeaderC>(), align_of::<HeaderC>(), offset_of!(HeaderC, kind), offset_of!(HeaderC, len), offset_of!(HeaderC, flags));
println!("HeaderRust: size {}", size_of::<HeaderRust>());
let v = Value { f: 1.0 };
// SAFETY: both fields are 4-byte plain numbers, so reading the bits as i32 is allowed.
println!("bits of 1.0f32: {:#x}", unsafe { v.i });
let _ = Value { i: 7 };
for t in [Tagged::Int(7), Tagged::Float(2.5)] {
match t {
Tagged::Int(i) => println!("int {i}"),
Tagged::Float(f) => println!("float {f}"),
}
}
println!("size of Tagged {} ; Option<Box<u8>> {} ; Box<u8> {}", size_of::<Tagged>(), size_of::<Option<Box<u8>>>(), size_of::<Box<u8>>());
}HeaderC: size 12 align 4 offsets kind 0 len 4 flags 8
HeaderRust: size 8
bits of 1.0f32: 0x3f800000
int 7
float 2.5
size of Tagged 8 ; Option<Box<u8>> 8 ; Box<u8> 8What the numbers say. With repr(C) the fields keep their declared order, so len starts at offset 4 (after padding behind the one-byte kind) and flags at 8, and the struct is padded to 12 bytes. The default layout needs only 8 bytes, which is Rust's reordering at work; the exact result is a property of this compiler version, not a promise, so never depend on it.
The union can be read as either field only inside unsafe, and nothing tells you which field is the valid one. The enum stores a tag and the data together (8 bytes here: a tag plus a 4-byte payload, padded to the payload's alignment), and match cannot read the wrong variant. Option<Box<u8>> is the same size as Box<u8>: the compiler uses the null pointer as None, which is why Option replaces nullable pointers at no cost.
How to do it#
- Struct only used inside Rust: no attribute needed. Struct that C reads or writes, or that is written to a file or socket as raw bytes:
#[repr(C)], with fields of fixed-width types (u32, notusize). - A C enum with numeric values that C code compares:
#[repr(C)] enum Kind { A = 0, B = 1 }for passing by value across the boundary. Receiving an arbitrary integer from C and converting it to such an enum without checking is undefined behaviour if the value is not one of the listed variants; take an integer type in the signature and convert with amatchorTryFrom. - A C tagged union (a
unionplus akindfield): port the logic as a Rustenumwith data. Convert from and to the C layout only at the boundary. - Bit fields have no direct Rust equivalent: store the integer and use masks and shifts, in small methods.
- Packed structs (
#pragma pack):#[repr(C, packed)], and do not take references to its fields (read them by value).
Common mistakes#
- Casting a byte buffer to a struct pointer and reading it. Alignment and endianness can differ; parse the fields from bytes explicitly (
u32::from_le_bytes). - Relying on the default layout in a file format or protocol.
- Treating a union as a convenience for "type punning" in ordinary code. Use
f32::to_bitsandfrom_bitsfor the example above.
Related questions#
Can I print the offsets of a C struct to compare with Rust?#
Yes. offset_of!(Type, field) is in the standard library. Compare against the offsets the C compiler reports for the same struct on the same target.
What about a flexible array member at the end of a C struct?#
It has no direct equivalent in safe Rust. Treat the header as a struct and the trailing data as a separate slice you create from the pointer and a length.
Sources#
- The Rust Reference, "Type layout": https://doc.rust-lang.org/reference/type-layout.html
std::mem::offset_of: https://doc.rust-lang.org/std/mem/macro.offset_of.html