diff options
| author | Val Markovic <val@markovic.io> | 2018-07-04 17:26:45 -0700 |
|---|---|---|
| committer | Val Markovic <val@markovic.io> | 2018-07-05 09:24:03 -0700 |
| commit | dc425e2e64863d4e1aa0f2bb41f7bfa3cd14b558 (patch) | |
| tree | a0d8472a2f91ff5fafb452e62ffd5a9b00c5547d | |
| parent | afaa40646542ca1e8fadb7e1d34197237e0fcd19 (diff) | |
| download | rust-dc425e2e64863d4e1aa0f2bb41f7bfa3cd14b558.tar.gz rust-dc425e2e64863d4e1aa0f2bb41f7bfa3cd14b558.zip | |
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.
| -rw-r--r-- | src/libcore/mem.rs | 5 |
1 files changed, 4 insertions, 1 deletions
diff --git a/src/libcore/mem.rs b/src/libcore/mem.rs index 84173654655..8fb4e0d6a02 100644 --- a/src/libcore/mem.rs +++ b/src/libcore/mem.rs @@ -229,6 +229,8 @@ pub fn forget<T>(t: T) { /// 2. Round up the current size to the nearest multiple of the next field's [alignment]. /// /// Finally, round the size of the struct to the nearest multiple of its [alignment]. +/// The alignment of the struct is usually the largest alignment of all its +/// fields; this can be changed with the use of `repr(align(N))`. /// /// Unlike `C`, zero sized structs are not rounded up to one byte in size. /// @@ -283,7 +285,8 @@ pub fn forget<T>(t: T) { /// // The size of the second field is 2, so add 2 to the size. Size is 4. /// // The alignment of the third field is 1, so add 0 to the size for padding. Size is 4. /// // The size of the third field is 1, so add 1 to the size. Size is 5. -/// // Finally, the alignment of the struct is 2, so add 1 to the size for padding. Size is 6. +/// // Finally, the alignment of the struct is 2 (because the largest alignment amongst its +/// // fields is 2), so add 1 to the size for padding. Size is 6. /// assert_eq!(6, mem::size_of::<FieldStruct>()); /// /// #[repr(C)] |
