Section 6 of 11

Memory & escape analysis

The compiler decides stack vs heap. Perf work in Go means "make this not allocate".

A value escapes when it outlives the function that created it — you return a pointer to it, store it in an interface, or capture it in a closure that survives. The compiler proves this and moves those values to the heap. In C returning &x is a dangling-pointer bug; in Go it is safe, and merely slower.

Stack, heap, and value semantics

go.dev playground

Try it: Locally you can see the decision with: go build -gcflags=-m main.go