Middle+
How is memory allocated in Golang? What is from the heap, and what is from the stack?
sobes.tech AI
Answer from AI
In Go, memory is allocated automatically, but conceptually there is a stack and a heap.
- Stack is used for local variables of functions and parameters. It is quickly allocated and freed when calling and returning from functions.
- Heap is used for objects that need to live longer than the function call, for example, if a variable is returned from a function or its address is stored outside the function.
The Go compiler and garbage collector decide where to place a variable (escape analysis). If a variable "escapes" from the stack (for example, its address is passed outside), it is placed on the heap.
Example:
func foo() *int {
x := 10 // local variable
return &x // x "escapes" to the heap
}
func main() {
p := foo() // p points to the heap
fmt.Println(*p)
}
Here, x will be placed on the heap because its address is returned from the function.