I'm a newbie to Go, coming from Node.JS.
In Node, if I run this:
function run(tick = 0) {
if (tick < 1000000) {
return run(tick + 1);
}
return 0;
}
console.log(run());
The program will crash because the maximum call stack size was exceeded.
If I do this in Go:
package main
import "fmt"
func run(tick int) (int) {
if (tick < 1000000) {
return run(tick + 1)
}
return 0
}
func main() {
fmt.Println(run(0))
}
This will run and print 0
to stdout.
My questions are:
- Is there a maximum number of calls above which the Go example I gave would fail?
- Is code like this an anti-pattern in Go?
In Go, goroutines do not have a fixed stack size. Instead they start small (with like 4KB), and grow / shrink when needed, seemingly giving the feeling of an "infinite" stack (of course it can't be truly infinite).
Yes, there is a limit. But this limit does not come from a call depth limit, but rather the stack memory limit. This limit is enforced by the Go runtime, but it is usually hundreds of MBs (or even a GB). On the Go Playground it's 250MB, which can be seen on this Go Playground Example.
On my local Linux 64-bit machine it's 1 GB.
Recommended reading: Dave Cheney: Why is a Goroutine's stack infinite?
Returning to your example: increasing the max recursion call to
1e9
will run out of the stack:This will result in: