Memory Layout and Repr Attribute in Rust
TL;DR: This guide covers memory layout and repr attributes in Rust. You’ll learn struct padding, alignment, memory optimization, and low-level data representation.
Introduction
Understanding memory layout is crucial for:
- Performance optimization
- FFI with C code
- Serialization
- Cache efficiency
Default Representation
Struct Padding
// Default representation (repr(Rust))
#[repr(C)] // Also available
struct MyStruct {
a: u8, // 1 byte + 7 padding
b: u64, // 8 bytes
c: u32, // 4 bytes + 4 padding
}
// Size: 24 bytes
Repr(C) for FFI
// C-compatible layout
#[repr(C)]
pub struct CInterface {
pub id: u32,
pub name: *const libc::c_char,
pub value: f64,
}
Repr(C) vs Repr(Rust)
| Aspect | repr(Rust) | repr(C) |
|---|---|---|
| Field order | Reordered for size | Preserved |
| Padding | Optimized | Platform C |
| FFI | Not safe | Safe |
| Size | Smaller | May vary |
Repr(packed)
Eliminate Padding
#[repr(packed)]
struct Packed {
a: u8,
b: u64,
c: u32,
}
// Size: 13 bytes (no padding)
Alignment Control
#[repr(align(64))]
struct Aligned64 {
data: [u8; 64],
}
// Align to 64-byte boundary for cache line
Conclusion
Memory layout controls:
- repr(Rust) - Optimized for Rust
- repr(C) - C compatibility
- repr(packed) - No padding
- repr(align(N)) - Custom alignment
Comments