Recursion is a programming technique where a function calls itself to solve smaller instances of the same problem until it reaches a base condition. Go supports recursion naturally, and itβs useful for tasks like factorial calculation, tree traversal, and more.
A recursive function has two main parts:
func factorial(n int) int { if n == 0 { return 1 // Base case: factorial of 0 is 1 } return n * factorial(n-1) // Recursive call } func main() { fmt.Println("Factorial of 5:", factorial(5)) // Output: 120 }
func fibonacci(n int) int { if n <= 1 { return n // Base cases: fib(0)=0, fib(1)=1 } return fibonacci(n-1) + fibonacci(n-2) // Recursive calls } func main() { for i := 0; i < 10; i++ { fmt.Printf("%d ", fibonacci(i)) } // Output: 0 1 1 2 3 5 8 13 21 34 }
Recursion in Go is a powerful tool to solve problems by breaking them down into smaller, similar subproblems. Proper use of base cases is essential to avoid infinite loops.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!