Recursive Functions in Go
Recursion is a programming technique in which a function calls itself directly or indirectly.
A recursive function usually contains two parts:
- Base Case: This is the termination condition of the recursion, preventing the function from calling itself infinitely.
- Recursive Case: This is the part where the function calls itself, used to break the problem down into smaller subproblems.
In Go, the use of recursion is similar to other languages, but some features of Go need to be kept in mind.
The syntax format is as follows:
func
recursion
()
{
recursion
()
/* the function calls itself */
}
func
main
()
{
recursion
()
}
Go supports recursion, but when using it, developers need to set an exit condition, otherwise the recursion will fall into an infinite loop.
Recursive functions are very useful for solving mathematical problems, such as computing factorials, generating Fibonacci sequences, and so on.
Factorial
The factorial of a positive integer is the product of the integer and all positive integers below it, denoted as n!. For example:
5! = 5 * 4 * 3 * 2 * 1 = 120
The following example implements factorial through a recursive function in Go:
Example
package
main
import
"fmt"
// recursive function to compute factorial
func
factorial
(
n
int
)
int
{
// base case
if
n
==
0
{
return
1
}
// recursive case
return
n
factorial
(
n
1
)
}
func
main
()
{
fmt
.
Println
(
factorial
(
5
))
// output: 120
}
Code explanation
- Base case: When
nWhen it equals 0, the function returns 1, because0!is defined as 1. - Recursive Case: the function returns
nmultiplied byfactorial(n-1)the result, gradually breaking the problem down into smaller subproblems.
The output of the above example is:
120
Fibonacci Sequence
The following example implements the Fibonacci sequence through a recursive function in Go:
Example
package
main
import
"fmt"
func
fibonacci
(
n
int
)
int
{
if
n <
2
{
return
n
}
return
fibonacci
(
n
2
)
fibonacci
(
n
1
)
}
func
main
()
{
var
i
int
for
i
=
0
;
i
<
10
;
i
++
{
fmt
.
Printf
(
"%d\t"
,
fibonacci
(
i
))
}
}
The output of the above example is:
0 1 1 2 3 5 8 13 21 34
Compute the square root
The following example implements square root computation using a recursive method in Go:
Example
package
main
import
(
"fmt"
)
func
sqrtRecursive
(
x
,
guess
,
prevGuess
,
epsilon
float64
)
float64
{
if
diff
:=
guess
guess
x
;
diff < epsilon &&
diff < epsilon
{
return
guess
}
newGuess
:=
(
guess
x
/
guess
)
/
2
if
newGuess
==
prevGuess
{
return
guess
}
return
sqrtRecursive
(
x
,
newGuess
,
guess
,
epsilon
)
}
func
sqrt
(
x
float64
)
float64
{
return
sqrtRecursive
(
x
,
1
.
0
,
0
.
0
,
1e
9
)
}
func
main
()
{
x
:=
25
.
0
result
:=
sqrt
(
x
)
fmt
.
Printf
(
"the square root of %.2f is %.6f\n"
,
x
,
result
)
}
In the above example, thesqrtRecursive The function implements square root computation using recursion.
sqrtRecursive The function accepts four parameters:
- x represents the number whose square root is to be found
- guess represents the current guessed square root value
- prevGuess represents the previous guess
- epsilon represents the precision requirement (i.e., how close to the square root)
The termination condition of the recursion is that the current guessed square root is very close to the previous guess, with a difference smaller than the given precision epsilon.
In the sqrt function, we call sqrtRecursive to compute the square root, passing in the initial value and precision requirement; then in the main function, we call the sqrt function to solve for the square root and print the result.
The output of the code above is:
25.00 的平方根为 5.000000
Advantages and disadvantages of recursion
Advantages
- simplicity: recursive code is usually more concise and easier to understand than iterative code.
- Problem decomposition: recursion is naturally suited to solving problems that can be broken down into similar subproblems, such as tree traversal and divide-and-conquer algorithms.
Disadvantages
- Performance overhead: recursive calls occupy stack space and may cause stack overflow, especially with deep recursion.
- Difficult to debug: recursive code can be harder to debug, especially when the recursion depth is large.
Recursion vs. iteration
Recursion and iteration are two different approaches to solving problems. Recursion solves a problem by having a function call itself, while iteration repeats a block of code through loop structures (such as for loops).
Recursion vs. Iteration
| Feature | Recursion | Iterate |
|---|---|---|
| Code conciseness | Usually more concise | Can be more verbose |
| Performance | Can be slower and occupy stack space | Usually faster and uses less memory |
| Applicable scenarios | Suitable for problems that can be broken into subproblems | Suitable for linear or simply repetitive problems |
Common applications of recursion
Recursion is widely used in many algorithms and data structures, for example:
- Tree and graph traversal: such as depth-first search (DFS).
- Divide and Conquer Algorithms: such as merge sort and quicksort.
- Dynamic Programming: such as the computation of the Fibonacci sequence.
File directory traversal
Example
import
(
"fmt"
"os"
"path/filepath"
)
func
walkDir
(
dir
string
,
indent
string
)
{
entries
,
err
:=
os
.
ReadDir
(
dir
)
if
err
!=
nil
{
return
}
for
_
,
entry
:=
range
entries
{
fmt
.
Println
(
indent
entry
.
Name
())
if
entry
.
IsDir
()
{
walkDir
(
filepath
.
Join
(
dir
,
entry
.
Name
()),
indent
" "
)
}
}
}
func
main
()
{
walkDir
(
"."
,
""
)
}
When using recursion in Go, pay special attention to the correctness of the base case (termination condition) to avoid infinite recursion. For performance-sensitive scenarios or those with potentially deep recursion, consider an iterative implementation or Go-specific mechanisms such as channel/goroutine.