Go Language Recursive Functions
Recursion is the process of a function calling itself during its execution.
The syntax is as follows:
func recursion() {
recursion() /* Function calls itself */
}
func main() {
recursion()
}
Go supports recursion. However, when using recursion, developers need to set a termination condition; otherwise, it will result in an infinite loop.
Recursive functions are very useful for solving mathematical problems such as calculating factorials and generating Fibonacci sequences.
Factorial
The following example demonstrates factorial calculation using a recursive function in Go:
Example
package main
import "fmt"
func Factorial(n uint64)(result uint64) {
if (n > 0) {
result = n * Factorial(n-1)
return result
}
return 1
}
func main() {
var i int = 15
fmt.Printf("%d! is %d\n", i, Factorial(uint64(i)))
}
The output of the above example is:
15! is 1307674368000
Fibonacci Sequence
The following example demonstrates the Fibonacci sequence using a recursive function in Go:
Example
package main
import "fmt"
func fibonacci(n int) int {
if n < 2 {
return n
}
return fibonacci(n-2) + fibonacci(n-1)
}
func main() {
var i int
for i = 0; i < 10; i++ {
fmt.Printf("%d\t", fibonacci(i))
}
}
The output of the above example is:
0 1 1 2 3 5 8 13 21 34