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

[Advanced Rust] 1.13. Memory Types Pt.1 - Alignment, Layout, and the Repr Attribute

SomeB1oody 2026年07月29日 02:34 3 次阅读 来源:Dev.to

1.13.1. The Basic Responsibility of Types Every Rust value has a type, and the responsibility of that type is to tell you how to interpret the bits in memory. For example, the bit pattern 0b10111101 has no meaning by itself, but: Interpreted as u8 , it becomes the number 189 Interpreted as i8 , it becomes the number -67 When you define a custom type, the compiler decides where each part of that type is placed in memory. 1.13.2. Alignment Alignment determines where a type’s bytes may be stored. Once a type’s representation is determined, you might think it can be stored anywhere in memory. In theory that is possible, but in practice computer hardware places constraints on where a given type can live. The most typical example is a pointer. A pointer points to bytes, not bits; one byte equals 8 bits. In other words, it does not point to an individual bit. So if a value of some type were placed at bit index 4 in memory, you would not be able to address it, because pointers address bytes rather than specific bits. That is why alignment is done at the byte level — that is, at 8-bit boundaries. For this reason, all values, regardless of type, must begin on a byte boundary . All types must be at least byte-aligned. In other words, the storage address must be a multiple of 8 bits. 1.13.3. Stricter Alignment Rules Some types have alignment requirements stricter than byte alignment. In CPU and memory systems, memory is often accessed in blocks larger than a single byte. For example, on a 64-bit CPU, most values are accessed in 8-byte blocks, and each operation begins at an address that is 8-byte aligned . This is also called the CPU word size. Of course, CPUs can also handle reads and writes of smaller values, as well as values that cross block boundaries. But as developers, we should try our best to ensure that hardware operates at its native alignment. For example, if the i64 value you want to read begins in the middle of an 8-byte block, then reading it requires at least tw

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