Go language recursive function
Recursion is the invocation of yourself in the process of running.
The syntax format is as follows:
1 func recursion () {2 /* */3}45func main () {6 Recursion ()7 }
The Go language supports recursion. But when we use recursion, the developer needs to set the exit criteria, or the recursion will fall into an infinite loop.
Recursive functions are useful for solving mathematical problems, like calculating factorial, generating Fibonacci sequences, and so on.
----------------------------------------------------------------------------------------------
Factorial
The following example uses the recursive function instance factorial of the Go language:
1 Package Main2 3Import"FMT"4 5Func factorial (xint) (Resultint) {6 ifx = =0 {7result =1; 8}Else {9result = x * factorial (X-1);Ten } One return; A } - - Func Main () { the varIint= the -Fmt. Printf ("the factorial of%d is%d\n", I, factorial (i)) -}
The output of the above instance execution is:
the 1307674368000
Fibonacci sequence
The following example implements the Fibonacci sequence with the recursive function of the Go language:
1 Package Main2 3Import"FMT"4 5Func Fibonacci (nint)int {6 ifN <2 {7 returnN8 }9 returnFibonacci (n2) + Fibonacci (n1)Ten } One A Func Main () { - varIint - fori =0; I <Ten; i++ { theFmt. Printf ("%d\t", Fibonacci (i)) - } -}
The output of the above instance execution is:
0 1 1 2 3 5 8 - + the
Go language recursive function