Go's escape analysis automatically moves variables from the stack to the heap if their lifetime exceeds the function scope.
Go's escape analysis determines at compile time whether a variable stays on the stack or moves to the heap based on its lifetime and usage. If a variable's lifetime extends beyond the function scope or its address is returned, the compiler moves it to the heap to prevent dangling pointers.
go build -gcflags="-m -m" yourpackage.go
The output shows which variables escape to the heap and why.
Escape analysis is the compiler's way of deciding where to store your data. It keeps short-lived variables in fast, temporary memory (stack) and moves long-lived ones to permanent memory (heap) if they need to survive after a function finishes. Think of it like a librarian deciding whether to keep a book on the desk for quick access or shelve it for long-term storage.