Stack vs Heap Allocation in Go

How Escape Analysis Works

Go's escape analysis automatically moves variables from the stack to the heap if their lifetime exceeds the function scope.

Go's escape analysis determines at compile time whether a variable stays on the stack or moves to the heap based on its lifetime and usage. If a variable's lifetime extends beyond the function scope or its address is returned, the compiler moves it to the heap to prevent dangling pointers.

go build -gcflags="-m -m" yourpackage.go

The output shows which variables escape to the heap and why.