In computer programming, a recursive function calls itself. For example,
Here, the recurse() function includes the function call within its body. Hence, it is a Go recursive function and this technique is called recursion.
Before you learn about recursion, make sure to know Go Functions.
Output
In the above example, we have created a function named countDown(). Note that we have added the function call inside the function.
Here, this is a recursive function call and we are decreasing the value of number in each call.
However, this function will be executed infinitely because we have added the function call directly within the function
To avoid infinite recursion, we use conditional statements and only call the function if the condition is met.
In this example, we will use an if...else statement to prevent the infinite recursion.
Output
In the above example, we have added the recursive call inside the if statement.
Here, we are calling the function only if the number is greater than 0.
If the number is not greater than 0, the recursion ends. This is called the stopping condition.
| number > 0 | Recursive Call | |
|---|---|---|
true | 3 | countDown(2) |
true | 2 | countDown(1) |
true | 1 | countDown(0) |
false | Countdown stops | function execution stops |

Output
In the above example, we have created a recursive function named sum() that calls itself if the value of number is not equal to 0.
In each iteration, we are calling the function by decreasing the value of number by 1.
Here's how the program works:
number is 50 which is not equal to 0. So, the else block is executed which returns 50 + sum(49).return 49 + sum(48) is executed.number becomes 0. When number is 0, return 0 is executed and it is added to the other values.main() function.Output
In the above example, we have created a recursive function named factorial() that calls itself if the value of num is not equal to 0.
In each call, we are decreasing the value of num by 1.
Here's how the program works:
