Stack vs Heap in Go

How Allocation Decisions Are Made

Go uses escape analysis to automatically allocate variables to the stack or heap based on their lifetime.

Go's compiler automatically decides whether to allocate a variable on the stack or the heap based on escape analysis. If the compiler determines a variable's lifetime extends beyond the function scope (e.g., it is returned or stored in a global), it "escapes" to the heap; otherwise, it stays on the stack for faster access. You can inspect these decisions by compiling with the -m flag to see optimization notes.

go tool compile -m yourfile.go

The output will list variables that escape to the heap, such as moves result to heap, indicating the compiler's allocation choice.