Recursive Functions in Go
- In Go, functions can be recursive, meaning a function can call itself. A recursive function must have a termination condition—a condition that eventually stops the recursion—to avoid infinite loops and excessive resource use.
Example 1: Counting Using Recursion
- In this example, the countUp function recursively prints numbers from the given starting point up to 10. The recursion stops when the number reaches 11.
package main
import (
"fmt"
)
func countUp(x int) {
if x == 11 {
return
}
fmt.Println(x)
countUp(x + 1)
}
func main() {
countUp(1)
}
import (
"fmt"
)
func countUp(x int) {
if x == 11 {
return
}
fmt.Println(x)
countUp(x + 1)
}
func main() {
countUp(1)
}
Output:
12
3
4
5
6
7
8
9
10
Why Use Recursion?
- Recursion is a powerful concept in programming and mathematics. It allows you to break down complex problems into simpler ones. When implemented correctly, recursive functions can be concise and elegant.
- However, use caution: recursive functions that lack a proper exit condition can lead to infinite loops and high memory usage.
Example 2: Factorial Using Recursion
- The factorial of a number n (denoted as n!) is the product of all positive integers less than or equal to n. For example, 4! = 4 × 3 × 2 × 1 = 24.
The following recursive function calculates the factorial of a number:
package main
import (
"fmt"
)
func factorial(x float64) float64 {
if x > 0 {
return x * factorial(x-1)
}
return 1
}
func main() {
fmt.Println(factorial(4))
}
import (
"fmt"
)
func factorial(x float64) float64 {
if x > 0 {
return x * factorial(x-1)
}
return 1
}
func main() {
fmt.Println(factorial(4))
}
Output:
24
Summary
- Recursive functions call themselves to solve a smaller piece of a problem.
- Always include a base case (stop condition) to avoid infinite recursion.
- Recursion can make your code cleaner and more expressive when used correctly.