Gaaker Go

Golang Recursion

When a function calls itself internally, it is called recursion.

Use a recursive function to calculate the Fibonacci sequence, this sequence starts from the third term, and each term is equal to the sum of the first two terms.

The following is a complete code example.

package main

import "fmt"

func fibonaci(i int) int {
    if i == 0 || i == 1 {
        return i
    }
    return fibonaci(i-1) + fibonaci(i-2)
}

func main() {
    for i := 0; i < 10; i++ {
        fmt.Printf("fibonacci(%d) is %d\n", i, fibonaci(i))
    }
}

Below is the program output:

fibonacci(0) is 0
fibonacci(1) is 1
fibonacci(2) is 1
fibonacci(3) is 2
fibonacci(4) is 3
fibonacci(5) is 5
fibonacci(6) is 8
fibonacci(7) is 13
fibonacci(8) is 21
fibonacci(9) is 34
< Recursion Recursion >