Recursion is the process of repeating a project in a similar way. Also applicable in programming languages, if a program allows you to invoke functions called by the same function, the recursive call function is used as follows.
Copy Code code as follows:
Func recursion () {
Recursion ()/* function calls itself * *
}
Func Main () {
Recursion ()
}
The Go programming language supports recursion, the function itself to invoke. But in the use of recursion, programmers need to be cautious about determining the exit condition of a function, otherwise it can cause an infinite loop.
Recursive function is very useful to solve many mathematical problems to calculate a number of factorial, produce Fibonacci series etc.
Number factorial
Here is an example that calculates the factorial used to use a recursive function by a given number:
Copy Code code as follows:
Package Main
Import "FMT"
func factorial (i int) {
if (I <= 1) {
Return 1
}
return I * factorial (i-1)
}
Func Main {
var i int = 15
Fmt. Printf ("Factorial of%d is%d\n", I, factorial (i))
}
Let's compile and run the above program, which will produce the following results:
Copy Code code as follows:
the Fibonacci series
The following is another example of generating a Fibonacci concatenation using a recursive function from a given number:
Copy Code code as follows:
Package Main
Import "FMT"
Func Fibonaci (i int) {
if (i = = 0) {
return 0
}
if (i = = 1) {
Return 1
}
Return Fibonaci (i-1) + Fibonaci (i-2)
}
Func Main () {
var i int
For i = 0; I < 10; i++ {
Fmt. Printf ("%d\t%n", Fibonaci (i))
}
}
Let's compile and run the above program, which will produce the following results:
Golang recursive judgment palindrome string
It is a classic question to judge the palindrome string.
The idea is to take the first character and the most one character and, if not unequal, to continue the process until the first and last characters meet or their distance of 1 o'clock. Indicate that they are palindrome strings.
The following code ignores the white space character Furu "1 1 2 1" to make it a palindrome string.
Copy Code code as follows:
Package Main
Import (
"FMT"
"OS"
"Strings"
"Unicode/utf8"
)
Func Dopalindrome (s string) bool {
If UTF8. Runecountinstring (s) <= 1 {
return True
}
WORD: = strings. Trim (S, "T \r\n\v")
The Sizeoffirst: = UTF8. Decoderuneinstring (Word)
Last, Sizeoflast: = UTF8. Decodelastruneinstring (Word)
If!= last {
return False
}
Return Dopalindrome (Word[sizeoffirst:len (Word)-sizeoflast])
}
Func ispalindrome (Word string) bool {
S: = ""
s = strings. Trim (Word, "\ t \r\n\v")
If Len (s) = 0 | | Len (s) = = 1 {
return False
}
return Dopalindrome (s)
}
Func Main () {
args: = os. Args[1:]
For _, V: = Range args {
OK: = Ispalindrome (v)
If OK {
Fmt. Printf ("%s\n", V)
}
}
}