Junior — Middle
When does the stack grow in Go goroutines?
sobes.tech AI
Answer from AI
In the Go language, each goroutine is initially created with a small stack (usually around 2 KB). The stack grows dynamically when during the execution of the goroutine there is a need for more memory for function calls or local variables.
This happens automatically: if the current stack is insufficient, the Go runtime allocates a new, larger stack, copies the data there, and continues execution. This approach allows efficient memory usage, as goroutines can have very small stacks that grow as needed.
It can be roughly illustrated as:
func recursive(n int) {
if n > 0 {
recursive(n-1) // with deep recursion, the stack will grow
}
}
If the call depth becomes large, the goroutine's stack will increase automatically.