Go language recursive function


Recursion means calling yourself during the running process.

The syntax format is as follows:

func recursion() {
   recursion() /* 函数调用自身 */
}

func main() {
   recursion()
}

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

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


Factorial

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

package main

import "fmt"

func Factorial(x int) (result int) {
  if x == 0 {
    result = 1;	
  } else {
    result = x * Factorial(x - 1);
  }
  return;
}

func main() {  
    var i int = 15
    fmt.Printf("%d 的阶乘是 %d\n", i, Factorial(i))
}

The execution output result of the above example is:

15 的阶乘是 1307674368000

Fibonacci Sequence

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

package main

import "fmt"

func fibonaci(n int) int {
  if n < 2 {
   return n
  }
  return fibonaci(n-2) + fibonaci(n-1)
}

func main() {
    var i int
    for i = 0; i < 10; i++ {
       fmt.Printf("%d\t", fibonaci(i))
    }
}

The execution output result of the above example is:

0	1	1	2	3	5	8	13	21	34