Go recursive function

In this example, we will show you how to create recursive function in Go with an example.

A recursive method calls itself to do its task. Recursion is a widely used approach to solve many programming tasks.

Go recursive function

In this code example, we calculate the factorial of three numbers:


package main

import "fmt"

func fact(n int) int {

    if n == 0 || n == 1 {
        return 1
    }

    return n * fact(n-1)
}

func main() {

    fmt.Println(fact(7))
    fmt.Println(fact(10))
    fmt.Println(fact(15))
}

Output:

5040
3628800
1307674368000

Inside the body of the fact function, we call the fact function with a modified argument. The function calls itself:



func fact(n int) int {

    if n == 0 || n == 1 {
        return 1
    }

    return n * fact(n-1)
}