2.40. Go language recursive function

发布时间 :2023-10-12 23:00:09 UTC      

Recursion is to call yourself in the process of running.

The syntax format is as follows:

func recursion() {
   recursion() /* Function call itself */
}
func main() {
   recursion()
}

Go language supports recursion. But when we use recursion, developers need to set exit conditions, otherwise recursion will fall into an infinite loop.

Recursive functions are very useful for solving mathematical problems, such as calculating factorials, generating Fibonacci sequences and so on.

2.40.1. Factorial #

The following example is passed through the Go recursive function instance factorial of the language:

Example #

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("The factorial of %d is %d\\n", i, Factorial(uint64(i)))
}

The output of the above example is as follows:

The factorial of 15 is 1307674368000

2.40.2. Fibonacci series #

The following example is passed through the Go the recursive function of the language implements the Fibonacci sequence:

Example #

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 example is as follows:

0    1    1    2    3    5    8    13    21    34

Principles, Technologies, and Methods of Geographic Information Systems  102

In recent years, Geographic Information Systems (GIS) have undergone rapid development in both theoretical and practical dimensions. GIS has been widely applied for modeling and decision-making support across various fields such as urban management, regional planning, and environmental remediation, establishing geographic information as a vital component of the information era. The introduction of the “Digital Earth” concept has further accelerated the advancement of GIS, which serves as its technical foundation. Concurrently, scholars have been dedicated to theoretical research in areas like spatial cognition, spatial data uncertainty, and the formalization of spatial relationships. This reflects the dual nature of GIS as both an applied technology and an academic discipline, with the two aspects forming a mutually reinforcing cycle of progress.