How to Use unsafe.Sizeof, Alignof, and Offsetof

Use unsafe.Sizeof, Alignof, and Offsetof to get the byte size, alignment, and field offset of Go types at compile time.

Use unsafe.Sizeof, unsafe.Alignof, and unsafe.Offsetof as compile-time functions to inspect the memory layout of Go types. unsafe.Sizeof returns the size in bytes, unsafe.Alignof returns the alignment requirement, and unsafe.Offsetof returns the byte offset of a field within a struct.

package main

import (
	"fmt"
	"unsafe"
)

type Point struct {
	X int
	Y int
}

func main() {
	var p Point
	fmt.Println("Size:", unsafe.Sizeof(p))
	fmt.Println("Align:", unsafe.Alignof(p))
	fmt.Println("Offset of Y:", unsafe.Offsetof(p.Y))
}