WEB DEVELOPER SITE

# Go - Recursion

Recursion is to call yourself during the running process.

syntax is as follows:

func recursion() {
recursion() /* Function call itself */
}

func main() {
recursion()
}

Go language supports recursion. But when we use recursion, the developer needs to set the exit condition, otherwise the recursion will fall into an infinite loop.

Recursive functions are very useful for solving mathematical problems, like calculating factorials, generating Fibonacci numbers, and so on.

## factorial

The following example uses the recursive function example factorial of the Go language:

## 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 Factorial is %d\n", i, Factorial(uint64(i)))
}

The above example execution output is:

`15 Factorial is 1307674368000`

## Fibonacci sequence

The following example implements the Fibonacci sequence through the recursive function of the Go language:

## 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 above example execution output is:

`0    1    1    2    3    5    8    13    21    34`