Recursion
Please refer to the recursive rookie Tutorial - go recursion
Recursion is not my focus, but the way to define skilled functions is.
The following function declaration method needs to be understood as follows:
In the Factorial function, the variable is declared at the same time as the function is declared before the result variable is used. If the variable is not declared at the same time as the function declaration, it will be undefined: result error.
package main
import "fmt"
func Factorial(n uint64)(result uint64) {
if (n > 0) {
result = n * Factorial(n-1)
return result
}
return 1
}
func main() {
var i int = 15
fmt.Printf("%d 的阶乘是 %d\n", i, Factorial(uint64(i)))
}
No result variable is introduced
package main
import "fmt"
func Factorial(n uint64) int64 {
if (n > 0) {
return n * Factorial(n-1)
}
return 1
}
func main() {
var i int = 15
fmt.Printf("%d 的阶乘是 %d\n", i, Factorial(uint64(i)))
}