Memory Layout of Go Types

Structs, Slices, Maps, Interfaces

Go structs are contiguous memory blocks, while slices, maps, and interfaces are heap-allocated references managed by headers or pointers.

Go stores structs as contiguous blocks of fields, slices as headers pointing to heap arrays, maps as pointers to hash tables, and interfaces as pairs of type and data pointers. Structs live inline or on the heap, while slices, maps, and interfaces always allocate their data on the heap.

// Struct: fields are contiguous
s := struct{ A int; B string }{A: 1, B: "hi"}

// Slice: header (ptr, len, cap) points to heap array
sl := []int{1, 2, 3}

// Map: pointer to hash table on heap
m := map[string]int{"a": 1}

// Interface: (type, data) pair
var i interface{} = "hello"