Principal
What is alignment and padding in Go, and how do they work?
sobes.tech AI
Answer from AI
In Go, alignment and padding are related to how the compiler arranges data in memory for optimal CPU performance.
Alignment is the requirement that a variable's address be a multiple of a certain number (usually the size of the data type). For example, int32 is usually aligned to 4 bytes.
Padding consists of extra bytes inserted by the compiler between structure fields to maintain alignment.
This affects the size of structures and the performance of access to them. For example:
package main
import "fmt"
type Example struct {
A byte // 1 byte
// 3 bytes padding for alignment of B
B int32 // 4 bytes
}
func main() {
var e Example
fmt.Println("Size of Example:", unsafe.Sizeof(e)) // Usually 8 bytes
}
Here, 3 bytes of padding are inserted between A and B so that B starts at an address divisible by 4, which speeds up memory access.