When to use recursive functions
To understand when to use a recursive function, we have to talk about the main trade-offs between iterative and recursive functions. But before we get to that, let’s start by saying that anything that can be implemented iteratively can also be implemented recursively. As such, each function that has a for
statement in Go can be replaced by an equivalent function that uses a recursive function call in place of the for
loop.
However, we might not always want to do so. The two main disadvantages of recursive functions are that they typically have greater time and space requirements. Calling a function multiple times creates multiple stack frames. These stack frames use up part of the working memory of our programs. Typically, each frame will contain a copy of the data from the frame below it (in a recursive function), which means that in the earlier Factorial example, each function call uses a similar amount of memory as the function that came...