The best Go language recursive function Tutorial In 2024, In this tutorial you can learn factorial,Fibonacci number,
Recursion, is to call their own in the process of running.
Syntax is as follows:
func recursion() { recursion() /* 函数调用自身 */ } func main() { recursion() }
Go language support recursion. But when we use recursion, developers need to set an exit condition, otherwise will fall into an infinite recursive loop.
Recursive function to solve the mathematical problem is very useful, like factorial, generate Fibonacci number and so on.
Go through the following examples recursive function factorial language examples:
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)) }
Examples of the implementation of the above output is:
15 的阶乘是 1307674368000
The following examples are achieved through recursive function Go language Fibonacci Sequence Fibonacci:
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)) } }
Examples of the implementation of the above output is:
0 1 1 2 3 5 8 13 21 34