golang recursive function example

Here is an example of a recursive function in Go (Golang):

package main

import "fmt"

func factorial(n int) int {
    if n == 0 {
        return 1
    }
    return n * factorial(n-1)
}

func main() {
    result := factorial(5)
    fmt.Println(result)
}

Explanation for each step:

  1. We start by defining a package called "main". In Go, the "main" package is the entry point for the program.

  2. We import the "fmt" package, which provides functions for formatted I/O operations such as printing to the standard output.

  3. We define a function called "factorial" that takes an integer parameter "n" and returns an integer. This function calculates the factorial of a given number recursively.

  4. Inside the "factorial" function, we check if the input parameter "n" is equal to 0. If it is, we return 1, as the factorial of 0 is defined to be 1.

  5. If the input parameter "n" is not 0, we return the product of "n" and the factorial of "n-1". This is the recursive step, where the function calls itself with a smaller value of "n" until it reaches the base case (n == 0).

  6. In the "main" function, we call the "factorial" function with a value of 5 and assign the result to the variable "result".

  7. Finally, we use the "Println" function from the "fmt" package to print the value of "result" to the standard output.

This program calculates the factorial of 5 (5!) using a recursive function. The factorial of a non-negative integer "n" is the product of all positive integers less than or equal to "n". In this case, 5! is equal to 5 4 3 2 1, which is 120.