Distinguish alignment from semantics
Distinguish alignment from semantics
A struct’s memory layout may contain padding between fields or at the end to satisfy alignment requirements. Field order can affect storage size, but do not assume one layout is portable across architectures. Size and alignment are representation properties; they do not replace the meaning or invariants of the record.
package main
import ( "fmt" "unsafe")
type Sample struct { Flag bool Count int64 Code byte}
func main() { var s Sample fmt.Println(unsafe.Sizeof(s) >= unsafe.Sizeof(s.Flag)+unsafe.Sizeof(s.Count)+unsafe.Sizeof(s.Code)) fmt.Println(unsafe.Offsetof(s.Count)%unsafe.Alignof(s.Count) == 0)}unsafe.Sizeof reports the size in bytes of the value’s representation, including struct padding. Alignof reports alignment; Offsetof reports a field offset from the struct start. These inspection operations do not mutate memory. Sizeof does not include separately referenced data, such as a slice backing array. Avoid unsafe memory manipulation.
Expected output:
truetrueObserve field order without assuming a fixed ABI
package main
import ( "fmt" "unsafe")
type A struct { X byte Y int64 Z byte}type B struct { Y int64 X byte Z byte}
func main() { a := A{X: 1, Y: 2, Z: 3} b := B{Y: a.Y, X: a.X, Z: a.Z} fmt.Println(a.X == b.X && a.Y == b.Y && a.Z == b.Z) fmt.Println(unsafe.Sizeof(a) >= 10, unsafe.Sizeof(b) >= 10)}The records contain the same logical field values, but their types differ because their field declarations are ordered differently. Both sizes must account for the field representations; padding may differ. Measure before optimizing, and use explicit serialization formats rather than assuming raw struct memory is a stable interchange format.
Expected output:
truetrue trueTry it locally
Define Entry with Code byte and Amount int64. Print whether its size is at least the sum of field sizes and whether Amount offset is a multiple of Amount alignment.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Structs and defined types 09: Distinguish alignment from semantics
Check the lesson objective before moving on.
Does unsafe.Sizeof on a struct include padding?
Does Sizeof include a slice field’s backing array?