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.
Code
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
CSS Flexbox PlaygroundInteractively test CSS flexbox container and item properties with a live preview. Adjust justify-content, align-items, flex-direction, and flex-grow to see layout changes.CSS Grid PlaygroundExperiment with CSS grid layout properties interactively. Define columns, rows, gaps, and areas while watching the grid template update in a live visual preview.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.