Where is memory stored in goroutines?
sobes.tech AI
Answer from AI
Memory for goroutines in Go is allocated on the heap, not on the stack, as in traditional OS threads. Each goroutine has its own stack, but it grows and shrinks dynamically as needed, starting from a very small size (about 2 KB). This allows efficient memory usage and the ability to run thousands of goroutines simultaneously.
The goroutine stack is managed by the Go runtime, which moves data between the stack and the heap if the stack becomes too small. The main data of a goroutine (local variables, function parameters) are stored on its stack, while objects allocated via new or make are stored on the heap.
Example:
func example() {
x := 10 // stored on the goroutine's stack
y := new(int) // allocated on the heap
*y = 20
fmt.Println(x, *y)
}
Thus, a goroutine's memory consists of its stack (dynamic, small) and the heap, which is shared among all goroutines and stores objects with dynamic lifetimes.