Recursive Functions
Go supports recursive functions. For a function to be recursive, it has to call itself and eventually reach a stop condition.
Below, testcount() calls itself over and over. Its data is the variable x, and each new call gets a value one higher (x + 1). Once x equals 11 (x == 11), the calls stop.
Example
Output: Go program and captured output
package main
import ("fmt")
func testcount(x int) int {
if x == 11 {
return 0
}
fmt.Println(x)
return testcount(x + 1)
}
func main() {
testcount(1)
}
Factorial Example
Recursion is a common idea in both mathematics and programming. Its benefit is that you can work through data step by step until you arrive at a result.
Take care when writing recursive functions, though. It is easy to end up with one that never finishes, or one that consumes too much memory or processor power. Done right, however, it can be both highly efficient and mathematically elegant.
In this example, factorial_recursion() calls itself with x reduced by 1 (x-1) each time. The calls stop once x is no longer greater than 0, which here means it has reached 0.
Example
Output: Go program and captured output
package main
import ("fmt")
func factorial_recursion(x float64) (y float64) {
if x > 0 {
y = x * factorial_recursion(x-1)
} else {
y = 1
}
return
}
func main() {
fmt.Println(factorial_recursion(4))
}