Rust Memory Layouts Explained: repr(Rust), Packed and Aligned Types
A technical deep-dive on DEV Community explores Rust's memory representation options for structs and other complex types. Unlike repr(C), Rust's default repr(Rust) allows the compiler to reorder struct fields — typically placing larger fields first — to minimize padding and reduce memory usage. The article demonstrates how a sample struct can shrink from 32 bytes under repr(C) to just 16 bytes with repr(Rust). It also covers repr(packed), which eliminates padding at the cost of slower or potentially crash-prone misaligned memory access, and repr(align(n)), which forces larger alignment to prevent false sharing across CPU cache lines in concurrent programs. Additional memory layouts for tuples, arrays, and unions are briefly outlined as well.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in