Escape analysis
Escape analysis is the compiler's decision that a variable must live on the heap because a pointer to it (or the value itself) can outlive the function. If it cannot escape, the variable stays on the stack.
Detailed Explanation
You write p := &Session{...}; return p. The Session cannot live in newSession's stack frame: that frame will be reused. The compiler allocates Session on the heap. You write s := Session{}; fmt.Println(s.Token) and never take a pointer that leaves the function: s can stay on the stack.
You do not opt in by keyword. There is no stack or heap in the source. &, storing a pointer in an interface, sending a pointer on a channel, closing over a variable in a returned closure, and assigning into a global all tend to escape. The compiler prints the decisions with go build -gcflags='-m'.
Interfaces box. var i any = n may heap-allocate n even though n is an int, because the interface must hold a pointer to a stable value. Small integers are sometimes optimized; do not depend on it in a tight loop that stores any.
Why it matters. Heap objects are garbage-collected. Stack objects vanish when the function returns, with no GC work. A pointer receiver on a tiny method can force the caller to heap-allocate the struct. That can be slower than copying the value. Profiles (allocs/op in benchmarks, pprof heap) tell you if escape analysis is the problem.
What it costs. The analysis is conservative: if the compiler is unsure, the value escapes. That is safe and sometimes wasteful. Do not rewrite readable code to "help" escape analysis until a benchmark shows the allocation. Then, pass values, preallocate slices, or avoid any in the hot path.
Code Examples
package main
type Session struct{ Token string }
func newSession(tok string) *Session {
s := Session{Token: tok} // escapes: returned
return &s
}
func local() int {
s := Session{Token: "x"} // can stay on stack
return len(s.Token)
}
func main() {
_ = newSession("a")
_ = local()
}go build -gcflags='-m' .
# ./file.go:7:2: moved to heap: sCommon Gotchas
Taking `&s` and storing it on a long-lived struct forces a heap alloc
the local "feels" stack-like and is not.
`fmt.Printf` and interfaces can make values escape
a debug print in a hot function can change allocation behaviour.
`-gcflags='-m'` is noisy
pipe through grep for `heap` on the files you care about.
Escape analysis is per build
inlining decisions change across Go versions.