Go Recursion

ht‮t‬ps://www.theitroad.com

Recursion is a technique in programming where a function calls itself repeatedly to solve a problem. Go supports recursion just like many other programming languages.

Here's an example of a recursive function in Go that computes the factorial of a number:

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

In this example, the factorial function takes an integer n as input and returns an integer that represents the factorial of n. If n is 0, the function immediately returns 1 since the factorial of 0 is 1. Otherwise, the function recursively calls itself with n-1 as the input argument and multiplies the result with n to obtain the factorial of n.

Here's an example of how the factorial function can be used:

fmt.Println(factorial(5)) // prints "120"

This code will call the factorial function with an input of 5, which will in turn call itself with an input of 4, then 3, then 2, and finally 1. Since the base case is reached when n equals 0, the function will begin returning values up the call stack, eventually resulting in a return value of 120.