Struct Field Offsets With unsafe

Read struct size, alignment, and field offsets with unsafe.Sizeof, Alignof, and Offsetof to see exactly where padding bytes come from.

GoData Integrity

Code

gosnippet
30 lines
package main

import (
	"fmt"
	"unsafe"
)

type Header struct {
	Version uint8
	Flags   uint16
	Length  uint32
	Offset  uint64
}

func main() {
	var h Header

	fmt.Println("size:", unsafe.Sizeof(h))
	fmt.Println("align:", unsafe.Alignof(h))

	// Struct field offsets: Offsetof exposes where each field starts
	fmt.Println("Version:", unsafe.Offsetof(h.Version))
	fmt.Println("Flags:", unsafe.Offsetof(h.Flags))
	fmt.Println("Length:", unsafe.Offsetof(h.Length))
	fmt.Println("Offset:", unsafe.Offsetof(h.Offset))

	// 对齐规则:uint16 落在 2 字节边界,uint32 落在 4,uint64 落在 8
	// 因此 Version 后会有 1 字节填充,Flags 后会有 2 字节填充
	fmt.Println("padding after Version:", unsafe.Offsetof(h.Flags)-unsafe.Sizeof(h.Version))
}

What the code carries out

Count the function main as the entire surface area of Struct Field Offsets With unsafe.

Applying it

Each run prints the 7 labeled blocks size:, align:, Version:, Flags:, Length:, Offset:, padding after Version: in source order.

Statements that matter

Flags   uint16

Interactive Tools for This Topic

FAQ

What does Struct Field Offsets With unsafe print when run?
Run it as a complete program — the output lines carry labels such as `size:`, `align:`, `Version:`.