Inspect Sizeof, Alignof and Offsetof
Inspect Sizeof, Alignof and Offsetof
Memory layout includes field sizes, alignment and possible padding. Sizeof measures the value itself in bytes; Alignof reports required alignment; Offsetof reports a field offset within a struct. These measurements depend on target architecture and implementation.
package main
import ( "fmt" "unsafe")
type Record struct { Flag byte Count int64}
func main() { var r Record fmt.Println(unsafe.Sizeof(r.Flag), unsafe.Sizeof(r.Count)) fmt.Println(unsafe.Offsetof(r.Count)%unsafe.Alignof(r.Count) == 0) fmt.Println(unsafe.Sizeof(r) >= unsafe.Offsetof(r.Count)+unsafe.Sizeof(r.Count))}Byte and int64 sizes are fixed, but alignment and padding can vary by target. The output checks relationships rather than assuming a particular offset. Sizeof includes struct padding. Do not use in-memory layout as a portable wire format; use explicit encodings.
Expected output:
1 8truetrueSlice descriptors versus their elements
package main
import ( "fmt" "unsafe")
func main() { a := make([]byte, 1) b := make([]byte, 100) fmt.Println(unsafe.Sizeof(a) == unsafe.Sizeof(b), len(a), len(b))}Sizeof on a slice measures its descriptor, not the underlying array or total heap cost. Likewise, Sizeof on an interface excludes the memory of the referenced value. Use profiling and workload measurements for memory usage.
Expected output:
true 1 100Try it locally
Compare the size of [4]uint16 and one uint16. Verify that the array is four times larger.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Reflection and unsafe 07: Inspect Sizeof, Alignof and Offsetof
Check the lesson objective before moving on.
Does Sizeof(slice) include the backing array?
What is a portable binary wire format approach?