Senior
What is escape analysis? How does it determine where a variable will be allocated (stack or heap)?
sobes.tech AI
Answer from AI
Escape analysis in Go is a process performed by the compiler that determines where a variable should be stored: on the stack or on the heap. If a variable "escapes" the scope of the function (for example, its address is returned or stored outside the function), it is allocated on the heap to remain accessible after the function completes.
How it works:
- The compiler analyzes the usage of the variable.
- If the variable is used only within the function and not passed outside, it is allocated on the stack (faster, automatically cleaned up).
- If the variable "escapes" (escape), for example, its address is stored in a global variable or returned from the function, it is allocated on the heap.
Example:
func f() *int {
x := 10
return &x // x "escapes" from the function, will be on the heap
}
func g() {
y := 20 // y does not escape, will be on the stack
fmt.Println(y)
}