How Stack vs Heap Allocation Works in Go

Go automatically places variables on the stack or heap based on their lifetime, which you can inspect using the -gcflags=-m compiler flag.

Go uses escape analysis at compile time to decide if a variable lives on the stack (fast, automatic cleanup) or the heap (managed by the garbage collector). If a variable's lifetime extends beyond the function scope (e.g., returned by reference or stored in a global), it escapes to the heap; otherwise, it stays on the stack. You can inspect this behavior using the compiler flag -gcflags=-m.

go build -gcflags=-m -gcflags=-m your_program.go

The output will list variables and explicitly state escapes to heap or does not escape.