Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Go language recursive function


May 11, 2021 Go


Table of contents


Go language recursive function

Recursive is to call yourself during the run.

The syntax format is as follows:

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

func main() {
   recursion()
}

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

Recursive functions are useful for solving mathematical problems, such as calculating factories, generating Fibonachi columns, and so on.


Factorial

The following examples are multiplied by recursive function instances in the 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 output of the above examples is:

15 的阶乘是 1307674368000

Fiponachi number column

The following example implements the Fibonachi number column through the recursive function of the Go language:

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 examples is:

0   1   1   2   3   5   8   13  21  34