今日已更新 450 条资讯 | 累计 28762 条内容
关于我们

[Advanced Rust] 1.14. Memory Types Pt.2 - Dynamically Sized Types and Wide Pointers, Packed Layouts, Larger Alignment for Speci…

SomeB1oody 2026年07月30日 14:16 2 次阅读 来源:Dev.to

Full title: [Advanced Rust] 1.14. Memory Types Pt.2 - Dynamically Sized Types and Wide Pointers, Packed Layouts, Larger Alignment for Specific Fields or Types, Memory Representation of Complex Types, and Repr Rust 1.14.1. repr(Rust) Remember the example in the previous article? That example used repr(C) , and the limitation of the C representation is that all fields must be placed in the same order as they are defined in the original struct. repr(Rust) is the default representation. It intentionally provides fewer layout guarantees than repr(C) : the compiler may reorder fields, and two types with the same fields in the same order are still not guaranteed to share a layout. Because the compiler may reorder fields (for example, placing larger fields first), padding can often be reduced. In the Foo example from the previous article, one possible optimized layout needs no padding. With fewer guarantees about layout, the compiler has room to rearrange things and produce efficient code. If repr(Rust) is used, then one possible memory layout of the Foo struct from above is: Code Field Type Size Default Representation Padding Final Alignment #[repr(Rust)] struct Foo { long: u64, 8 bytes 8-byte aligned 8 bytes normal: u32, 4 bytes 4-byte aligned short: u16, 2 bytes 2-byte aligned small: u8, 1 byte 1-byte aligned tiny: bool, 1 byte 1-byte aligned } Total 16 bytes The compiler first orders the fields by size, putting the largest first so that it can determine what alignment the struct should use. In this example, u64 is the largest and takes 8 bytes, so the struct is aligned to 8 bytes The compiler then looks at the remaining fields and sees that their total size is exactly 8 bytes, so it can place them together and avoid padding In the end, this struct only needs 16 bytes, which saves half the memory compared with repr(C) This is more efficient, but compilation time may be a little longer 1.14.2. Packed Layouts You can tell the compiler that no padding is needed between fiel

本文内容来源于互联网,版权归原作者所有
查看原文