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
Each recursive call uses memory to remember where to return. Very deep recursion can use too much memory, so use a loop when the input could require an unknown number of calls. This example's result can also grow beyond the largest int; limit the input to values whose result fits.
Enjoyed this? Get more software craft delivered to your inbox.