Golang - Recursion

Golang - Recursion

Recursion

The programming language Golang is known for its simplicity, efficiency 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 applied. Recursion is when a function calls itself to achieve the expected goal.

Efficiency

Always verify if the recursion solution will be efficient due to several executed calls.

Alternatives

Always verify the possibility of apply other solutions with iterations encouraging 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        

要查看或添加评论,请登录

Daniel M.的更多文章

  • Golang HTTP Requests - Complete Guide

    Golang HTTP Requests - Complete Guide

    HTTP Requests In Go, we can use the net/http package to make http requests. We will use this public endpoint to make a…

  • Using structs with Redis and Golang

    Using structs with Redis and Golang

    Many times, we will need to store a struct in Redis instead of storing only separate fields. We can store a struct like…

  • Redis Hash

    Redis Hash

    A Redis Hash is a data structure in Redis that stores a set of key-value pairs, similar to an object or map in…

  • Go Nested Templates

    Go Nested Templates

    We can nest templates in Go, allowing us to create smaller parts of a template, similar to components. In this example,…

  • Go Templates 02 - Conditionals

    Go Templates 02 - Conditionals

    Conditional Templates Another very common feature we need when working with templates is the use of conditions. For all…

  • Go Templates 01 - Basics

    Go Templates 01 - Basics

    Templates Go provides a powerful template system through the text/template and html/template packages, enabling the…

  • Go - sorting slices

    Go - sorting slices

    In Go, sorting a slice is often necessary when working with data that needs to be organized or structured for better…

  • Go - Arrays

    Go - Arrays

    Arrays Array is a data structure used to store a sequence of elements of same type in a fixed-size. An array is stored…

  • Redis SET command.

    Redis SET command.

    Redis set command SET We can set a string value to a key using the set command. In order to check if the value was…

社区洞察

其他会员也浏览了