Senior
How to determine whether a variable will be located on the heap or on the stack? What is escape analysis and how does it work?
sobes.tech AI
Answer from AI
In Go, the placement of a variable (on the stack or heap) is determined by the compiler through escape analysis. If a variable "escapes" outside the function, for example, by being returned or stored in a global scope, it is placed on the heap to preserve its lifetime.
Escape analysis is a compiler process that determines which variables can be allocated on the stack (faster, with automatic deallocation) and which must be allocated on the heap (with lifetime managed by the garbage collector).
Example:
func foo() *int {
x := 10 // x may "escape"
return &x // returning the address of x means x should be on the heap
}
func bar() {
y := 20 // y does not escape the scope of bar
fmt.Println(y) // y can be on the stack
}
In the first case, variable x will be placed on the heap, while in the second case, y will be on the stack.