Go by Example

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 to solve a smaller version of a problem. A base case stops the calls. This factorial function expects a nonnegative input.

Each recursive call reduces n by one until it reaches the base case, zero.

package main
 
import "fmt"
 
func factorial(n int) int {
    if n == 0 {
        return 1
    }
    return n * factorial(n-1)
}
 
func main() {
    fmt.Println(factorial(5))
}

In production

Go grows call stacks as needed, but deep recursion can still exhaust available memory or reach runtime limits. Use a loop or explicit stack when input depth is unbounded. This example can also overflow int for large values, so validate its input range.

Enjoyed this? Get more software craft delivered to your inbox.