Skip to main content

Recursive Functions

Go supports recursive functions. For a function to be recursive, it has to call itself and eventually reach a stop condition.

Below, testcount() calls itself over and over. Its data is the variable x, and each new call gets a value one higher (x + 1). Once x equals 11 (x == 11), the calls stop.

Example

Prompt
Create a recursive function testcount that prints numbers from x up to 10, incrementing by 1 each call. Stop when x equals 11.
Output: Go program and captured output

Factorial Example

Recursion is a common idea in both mathematics and programming. Its benefit is that you can work through data step by step until you arrive at a result.

Take care when writing recursive functions, though. It is easy to end up with one that never finishes, or one that consumes too much memory or processor power. Done right, however, it can be both highly efficient and mathematically elegant.

In this example, factorial_recursion() calls itself with x reduced by 1 (x-1) each time. The calls stop once x is no longer greater than 0, which here means it has reached 0.

Example

Prompt
Create a recursive function factorial_recursion that calculates the factorial of a float64 number. Call it with 4 and print the result.
Output: Go program and captured output