The programming technique by which a program calls itself is called recursion. Recursion, as an algorithm, is widely used in programming languages, especially in computation. A procedure or function in the introduction to the definition or call their own, directly or indirectly, with a kind of method, it is usually the problem of a large complex layers into a similar to the original problem of smaller problems to solve, the recursion strategy only a small number of procedures can be required to describe the problem solving process of repeatedly calculation, greatly reduces the amount of program code.

Recursion is the ability to define an infinite collection of objects in finite statements. In general, recursion needs to have:

  1. The boundary conditions
  2. Recursive forward section
  3. Recursively return segment.

At this point, when the boundary conditions are not satisfied, the recursion forward; When the boundary condition is satisfied, the recursion returns, for example:

graph TD; Start --> recursion 1 recursion 1 satisfy --> recursion 2; Recursive 2-- satisfy --> recursive 3; Recursion 3-- not satisfied --> recursion 2 Recursion 2-- return --> recursion 1 Recursion 1-- end --> output

An example of recursion in Go is as follows:

func recursion(a) {
   recursion() /* Function calls itself */
}

func main(a) {
   recursion()
}
Copy the code

Fibonacci

The Fibonacci sequence, also known as the Golden section sequence, was introduced by mathematician Leonardoda Fibonacci using rabbit breeding as an example. It is also known as the Rabbit sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34…

Mathematically, the Fibonacci sequence is defined recursively as follows: F(0)=0, F(1)=1, F(n)=F(n-1)+F(n-2) (n ≥ 2, n ∈ N*).

In algorithm teaching, the Fibonacci sequence is often used as a case study of recursive courses. To calculate the Fibonacci sequence in Go, just use the following code:

package main

import "fmt"

func fibonacci(n int) int {
  if n < 2 {
   return n
  }
  return fibonacci(n - 2) + fibonacci(n - 1)}func main(a) {
    var i int
    for i = 0; i < 20; i++ {
       fmt.Printf("%d ", fibonacci(i))
    }
}
Copy the code

Run the program, that is, the output of 1~20 elements of the sequence.