Recursion
Functions that call themselves - Go supports recursion with automatic goroutine stack growth, though deep trees are better handled with an explicit stack.
A recursive function calls itself until it reaches a base case. Go supports recursion with automatically growing goroutine stacks - you do not need to worry about a fixed stack size as you would in C.
Classic factorial: the base case returns immediately; the recursive case reduces the problem by one step each call.
package main
import "fmt"
func factorial(n int) int {
if n == 0 {
return 1 // base case
}
return n * factorial(n-1)
}
func main() {
fmt.Println(factorial(5)) // 120
fmt.Println(factorial(10)) // 3628800
}Two functions can call each other mutually. Go resolves the forward reference at link time, so you only need to declare both functions in the same package.
package main
import "fmt"
func isEven(n int) bool {
if n == 0 {
return true
}
return isOdd(n - 1)
}
func isOdd(n int) bool {
if n == 0 {
return false
}
return isEven(n - 1)
}
func main() {
fmt.Println(isEven(8)) // true
fmt.Println(isOdd(7)) // true
}A closure can refer to itself by assigning it to a variable before the function literal is called.
package main
import "fmt"
func main() {
var fib func(n int) int
fib = func(n int) int {
if n <= 1 {
return n
}
return fib(n-1) + fib(n-2)
}
for i := 0; i < 8; i++ {
fmt.Printf("fib(%d) = %d\n", i, fib(i))
}
}In production
Go does not optimize tail calls - every recursive call adds a frame to the goroutine's stack. Go grows that stack automatically up to a configurable limit (default 1 GB) before panicking with a stack overflow. For deep traversal - parsing deeply nested JSON, walking large directory trees, traversing binary trees with millions of nodes - an explicit stack (a slice used as a LIFO queue) is more predictable: you control memory usage, avoid GC pressure from many small frames, and can apply a depth limit cleanly. Save recursion for cases where the problem depth is bounded and the recursive form is substantially clearer.
Enjoyed this? Get more essays on software craft delivered to your inbox.
Subscribe free