Skip to content

Commit dc425e2

Browse files
committed
Clarifying how the alignment of the struct works
The docs were not specifying how to compute the alignment of the struct, so I had to spend some time trying to figure out how that works. Found the answer [on this page](http://camlorn.net/posts/April%202017/rust-struct-field-reordering.html): > The total size of this struct is 5, but the most-aligned field is b with alignment 2, so we round up to 6 and give the struct an alignment of 2 bytes.
1 parent afaa406 commit dc425e2

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

src/libcore/mem.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,8 @@ pub fn forget<T>(t: T) {
229229
/// 2. Round up the current size to the nearest multiple of the next field's [alignment].
230230
///
231231
/// Finally, round the size of the struct to the nearest multiple of its [alignment].
232+
/// The alignment of the struct is usually the largest alignment of all its
233+
/// fields; this can be changed with the use of `repr(align(N))`.
232234
///
233235
/// Unlike `C`, zero sized structs are not rounded up to one byte in size.
234236
///
@@ -283,7 +285,8 @@ pub fn forget<T>(t: T) {
283285
/// // The size of the second field is 2, so add 2 to the size. Size is 4.
284286
/// // The alignment of the third field is 1, so add 0 to the size for padding. Size is 4.
285287
/// // The size of the third field is 1, so add 1 to the size. Size is 5.
286-
/// // Finally, the alignment of the struct is 2, so add 1 to the size for padding. Size is 6.
288+
/// // Finally, the alignment of the struct is 2 (because the largest alignment amongst its
289+
/// // fields is 2), so add 1 to the size for padding. Size is 6.
287290
/// assert_eq!(6, mem::size_of::<FieldStruct>());
288291
///
289292
/// #[repr(C)]

0 commit comments

Comments
 (0)