liveBook · Manning

Data alignment

As explained in 100 Go Mistakes and How to Avoid Them

Data alignment is the placement of data in memory at addresses satisfying the alignment requirements of the data type or hardware.

Data alignment places values at addresses suitable for their type or hardware. Without it, a value can span two machine words and require two memory accesses; alignment can also introduce padding. section 12.4

Go guarantees alignment for these types:

  • byte, uint8, and int8: 1 byte; uint16 and int16: 2 bytes. section 12.4
  • uint32, int32, and float32: 4 bytes; uint64, int64, float64, and complex64: 8 bytes; complex128: 16 bytes. section 12.4
  • Struct fields can create internal and trailing padding when their addresses must satisfy stricter alignment. section 12.4

Reordering fields reduces padding

type Foo struct { b1 byte; i int64; b2 byte } occupies 24 bytes because the int64 requires padding before it and the struct requires trailing padding. Reordering the fields as int64, byte, byte reduces the struct to 16 bytes. This matters when many values are stored in a slice: more relevant fields fit in each cache line. section 12.4

type Foo struct {
    i  int64
    b1 byte
    b2 byte
}

Inspect the compact field ordering that avoids the larger padding layout. section 12.4

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Traces word-spanning accesses, alignment guarantees, struct padding, field reordering, and cache-line effects.
Examples
Uses int32 and int64 variables, padded Foo structs, reordered fields, and slice iteration.
What it assumes
Assumes familiarity with Go variables, structs, slices, and basic memory-access concepts.
What you can do after
Evaluate struct layouts and reorder fields to reduce padding and improve memory efficiency.
How it connects
Connects data alignment with memory access, struct layout, padding, cache lines, and CPU performance.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.