Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 147 ยท Structs and Methods

Struct Memory Layout and Alignment

Learn how Go lays out structs in memory - sizes and alignment of types, padding, unsafe.Sizeof and Offsetof, reordering fields to save space, and the empty struct.

When you declare a struct, Go stores its fields one after another in memory. You might expect the size of the struct to be the sum of its fields, but it usually isn't. CPUs read memory fastest when a value sits at an address that is a multiple of its size, so the compiler inserts invisible gaps called padding to keep every field aligned. The order of your fields therefore changes how much memory a struct occupies, sometimes by a large factor when you create millions of them.

This lesson shows how to measure sizes with unsafe.Sizeof, unsafe.Alignof and unsafe.Offsetof, explains the alignment rules, demonstrates how reordering fields shrinks a struct, and ends with the zero-size struct{} and its uses. The numbers below are for a 64-bit platform (amd64 or arm64), which is what our server and nearly every modern machine use; 32-bit systems differ. Most programs never need this level of detail, but it is valuable for performance work and for understanding how structs really look in memory.

Size and alignment of basic types

Every type has a size (bytes it occupies) and an alignment (the address multiple it requires). The unsafe package exposes both. The unsafe import is the price of admission for these functions, but Sizeof, Alignof and Offsetof are completely safe: they are evaluated at compile time and only report numbers:

Go Sizes and alignments of basic types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The pattern: a number's alignment equals its size (up to 8 bytes on a 64-bit machine), a string is two words (a pointer and a length = 16 bytes), a slice is three words (pointer, length, capacity = 24 bytes), a map and a pointer are one word, and an interface is two words (type and data). An array has the alignment of its element, not of the whole array: [3]int16 is 6 bytes with alignment 2. Notice that Sizeof reports the size of the header for strings, slices and maps, not the data they point to.

How a struct is laid out

The rules for a struct are simple:

  1. Fields are placed in declaration order. Go never reorders them for you.
  2. Each field starts at the next offset that is a multiple of its own alignment, so padding goes before a field when needed.
  3. The struct's alignment is the largest alignment among its fields.
  4. The struct's total size is rounded up to a multiple of its alignment, so arrays of the struct keep every element aligned. That adds padding at the end.

unsafe.Offsetof(s.field) reports where a field starts. Look at a struct whose fields are mixed unwisely:

Go Padding between fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The fields add up to only 1 + 8 + 1 + 4 = 14 bytes, but the struct takes 24. Here is the picture, with . marking padding:

TEXT
offset: 0  1..7      8..15  16 17..19 20..23
        A  padding   B      C  padding D
        [A][.......][B.......][C][...][D...]   -> 24 bytes

A sits at 0, then B needs an 8-byte boundary, so 7 bytes of padding follow. C is placed right after B at 16, and D needs a 4-byte boundary, so it waits until 20. The total is 24, already a multiple of the alignment (8).

Reordering fields to save space

Since padding comes from awkward ordering, you can often shrink a struct by sorting fields from the largest alignment to the smallest. The same four fields, in a better order:

Go Reordering fields to shrink a struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Compact is 16 bytes: B fills 0 to 7, D fills 8 to 11, the two bools sit at 12 and 13, and two bytes of trailing padding round the size up to 16. A third saved memory per value, which at a million values is 8 MB less, and better cache use because more values fit in a cache line.

Go does not reorder fields automatically because the order can matter for other reasons: cgo and binary file layouts depend on declaration order, and readability suggests grouping related fields. There is no promise that a future compiler won't reorder; the rule today is that you decide.

Don't reorder structs prematurely. Group fields by meaning first. Optimize only when the struct appears in huge slices or maps, measured with a benchmark or a memory profile. The fieldalignment analyzer (from golang.org/x/tools) can list structs that would shrink.

Strings, slices and nested structs

A struct field of type string takes 16 bytes regardless of the text, and a slice takes 24. Nested structs are laid out inline, with their own alignment:

Go Nested structs and headers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The last line prints true: Sizeof is a property of the type, not the data. A string's text lives elsewhere, and Sizeof counts only the 16-byte header stored in the struct. To measure total memory including referenced data you need a runtime measurement such as testing.AllocsPerRun, a benchmark or a heap profile.

Arrays and padding at the end

Because a struct's size is rounded up to its alignment, a slice of structs wastes padding in every element. This is why a struct with an int64 and a single bool takes 16 bytes, not 9:

Go Trailing padding adds up

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Storing 1000 items as a slice of structs uses 16,000 bytes, while two parallel slices ("structure of arrays") use 9,000. The second layout is also friendlier to loops that touch only one field. It is a trade-off: the code is less convenient than items[i].Flag.

The empty struct

A struct with no fields, struct{}, has size zero. It occupies no memory and all its values are equal. That makes it the perfect type for "I only care that something happened or exists":

Go The empty struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

You will see map[T]struct{} as a set (Go has no built-in set type), chan struct{} for signals such as "done" or "quit" (see Channels), and struct{} as a placeholder in generic code. A caution: a zero-size field at the very end of a non-empty struct gets padded so that taking its address cannot point past the allocation, which is why trailing struct{} fields can unexpectedly increase size. Put them first or avoid them.

Atomics and 64-bit alignment

On 32-bit platforms, 64-bit values accessed through sync/atomic function calls must be 8-byte aligned, and the compiler only guarantees that for the first word of an allocated struct. The modern fix is to use the typed atomics (atomic.Int64, atomic.Uint64, atomic.Pointer[T]), which handle alignment themselves. On 64-bit systems you will never meet the problem.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. On a 64-bit platform, what is unsafe.Sizeof of struct { A bool; B int64 }?

    B must start at a multiple of 8, so 7 bytes of padding follow A. The total is 16, already a multiple of the alignment 8.
  2. 2. What is the size of a Go string value (the header) on a 64-bit platform?

    A string header holds a pointer and a length, 8 bytes each, no matter how long the text is.
  3. 3. Which field order is usually the most compact?

    Putting wide, strictly aligned fields first leaves small fields to fill the end, which minimizes padding.
  4. 4. What does unsafe.Sizeof(struct{}{}) return?

    The empty struct has size zero, which is why map[string]struct{} works as a memory-cheap set.
  5. 5. Does Go reorder struct fields to reduce padding?

    Go lays fields out in the order you wrote them, so reordering is your job when size matters.

Summary

  • Every type has a size and an alignment; unsafe.Sizeof, Alignof and Offsetof report them at compile time.
  • Each field starts at a multiple of its own alignment, and the struct size is rounded up to the struct's alignment.
  • The compiler never reorders fields; sorting from largest to smallest alignment usually minimizes padding.
  • Strings (16), slices (24), maps and pointers (8) and interfaces (16) are headers; their data lives elsewhere.
  • Only optimize layout where millions of values exist and measurement shows it matters.
  • struct{} takes zero bytes: use map[T]struct{} for sets and chan struct{} for signals.

Next: Interfaces