Stack vs heap
Each goroutine has a stack for locals that do not escape. The heap holds values that outlive a frame or cannot be proven stack-safe. The compiler picks; you see the effect in allocations and GC.
Detailed Explanation
A stack is LIFO storage for function frames: parameters, locals, return addresses. When a function returns, its frame is gone. The heap is a shared pool the GC manages. A *Session you return, a slice backing array that escapes, a closure's captured variables — those are heap.
Goroutine stacks grow. Unlike a fixed 8 MiB OS thread stack, a Go stack starts small and copies to a larger stack when a call would overflow. Deep recursion can still exhaust memory by growing without bound. Huge value locals (var buf [1 << 20]byte) on each frame multiply with depth.
Heap is shared. Any goroutine with a pointer can read the object. That is why heap data needs synchronization if two goroutines write it. Stack data is private to the goroutine unless you take a pointer and share it (which usually escapes to the heap anyway).
There is no malloc in application code. make, new, composite literals, and append allocate. Stack vs heap is not in the syntax. new(T) is always a pointer; the T may still be stack-allocated if it does not escape (the compiler can allocate the pointed-to value on the stack and return a pointer into the frame only if that pointer does not escape — if it does, both move to the heap).
What it costs. Stack allocation is a pointer bump and is freed for free. Heap allocation updates the allocator and eventually the GC. Prefer stack by not letting pointers escape, when a benchmark shows it matters. Prefer heap when the value must be shared or large enough to blow a stack frame.
Code Examples
package main
func stackLocal() int {
n := 3 // stack
return n
}
func heapPtr() *int {
n := 3
return &n // n on heap
}
func main() {
_ = stackLocal()
_ = heapPtr()
}func hugeStack() {
var buf [1 << 20]byte // 1 MiB on this frame
buf[0] = 1
}Common Gotchas
A large array local can explode stack use in recursion
use `make([]byte, n)` so it lives on the heap once.
Sharing a pointer to a stack-looking local is how it becomes heap
the compiler is conservative.
Each goroutine has its own stack, one shared heap
Each goroutine has its own stack, one shared heap
`pprof` heap profiles show heap, not stack frames
`pprof` heap profiles show heap, not stack frames