Ad space (banner)
๐ŸนGo Lessons
Lesson 12 / 68

Recursive Functions

In this lesson you will learn how to write a recursive function in Go and understand how a function can call itself. This is for anyone searching for "Go recursive functions how to use".

A recursive function is a function that calls itself. It suits work that repeats the same calculation pattern, such as "n! = n x (n-1)!".

The sample code has factorial call itself in the form n * factorial(n-1) to compute the factorial of 5. The stopping condition (here n <= 1) is what makes the chain of calls come to an end.

A common stumbling block for beginners is forgetting that stopping condition. Without one, the function calls itself forever and the program crashes. Deep recursion also consumes a lot of stack, so in practice it is worth considering whether a loop would do instead.

In real-world development recursion is a natural fit for traversing tree structures and folder hierarchies, though a loop is often preferred where performance matters.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)