Golang recursion
Recursion
The programming language Golang is known for its simplicity, enfficiency and for work really well with concurrency. The use of recursion isn’t very common in Go, but in some situations is the best solution to be applyed.
Recursion is when a function calls itself to achieve the expected goal.
Eficiency
Allways verify if the recursion solution will be efficient due to several executed calls.
Alternatives
Allways verify the possibility of apply other solutions with iterations encouranging code clarity.
Code
An example of countdown in Go is below.
package main
import "fmt"
func countdown(number int) {
if number >= 0 {
fmt.Printf("Current value: %d\n", number)
countdown(number - 1)
} else {
fmt.Println("Finished")
}
}
func main() {
countdown(10)
}
>> Current value: 10
>> Current value: 9
>> Current value: 8
>> Current value: 7
>> Current value: 6
>> Current value: 5
>> Current value: 4
>> Current value: 3
>> Current value: 2
>> Current value: 1
>> Current value: 0
>> Finished