Go language recursive function


Release date:2023-09-19 Update date:2023-10-13 Editor:admin View counts:247

Label:

Go language recursive function

Recursion is to call yourself in the process of running.

The syntax format is as follows:

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

Go language supports recursion. But when we use recursion, developers need to set exit conditions, otherwise recursion will fall into an infinite loop.

Recursive functions are very useful for solving mathematical problems, such as calculating factorials, generating Fibonacci sequences and so on.

Factorial

The following example is passed through the Go recursive function instance factorial of the 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("The factorial of %d is %d\\n", i, Factorial(uint64(i)))
}

The output of the above example is as follows:

The factorial of 15 is 1307674368000

Fibonacci series

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

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 as follows:

0    1    1    2    3    5    8    13    21    34

Powered by TorCMS (https://github.com/bukun/TorCMS).