stack overflow
Go Programming Language
Severity: CriticalWhat Does This Error Mean?
Go panics with a stack overflow when a goroutine's call stack grows too large. This almost always means infinite or uncontrolled recursion. The goroutine stack has a default limit of 1 GB — hitting it means something is very wrong.
Affected Models
- Go 1.21
- Go 1.22
- Go 1.23
- Go 1.24
Common Causes
- A recursive function with no base case — it calls itself forever
- Mutual recursion — function A calls function B, which calls function A
- A base case that is never reached due to a logic error
- Recursive data structure traversal on a deeply nested or cyclic structure
- Accidentally calling a method on a type that wraps the same method
How to Fix It
-
Read the panic stack trace — look for the same function name repeating over and over.
Go prints a truncated trace. The repeated function is your infinite recursion entry point.
-
Find the recursive function and verify its base case is correct and reachable.
Every recursive function needs a condition that stops the recursion. If it's missing or wrong, you get this panic.
-
Add a print statement or counter at the start of the recursive function to trace calls.
fmt.Println("depth:", depth) helps you see how deep the recursion goes before crashing.
-
Convert deep recursion to an iterative approach using a stack data structure.
Use a slice as a stack: push items, pop and process them in a loop. This avoids goroutine stack growth entirely.
-
For recursive struct methods, check that you are not calling the same method in a loop.
A common mistake: implementing String() for a struct, then calling fmt.Sprintf on the struct inside String() — this recurses infinitely.
When to Call a Professional
If the stack trace is very long and hard to follow, ask a senior developer to help trace the recursion path. Cyclic data structures require special traversal logic — this is not always straightforward.
Frequently Asked Questions
What is the default goroutine stack size in Go?
Goroutines start with a small stack — around 8 KB. Go grows the stack dynamically as needed, up to a default max of 1 GB. Hitting 1 GB means you have runaway recursion.
Can I increase the goroutine stack limit?
Yes — use runtime/debug.SetMaxStack() to change the limit. But this is almost never the right fix. The real fix is eliminating the infinite recursion.
Is Go's recursion slower than iteration?
In most cases, yes — function calls have overhead. For deep recursion on large data, iterative approaches with an explicit stack are faster and safer. Go does not currently perform tail call optimization.