loops-in-golang-explained

Loops in Golang

Home » Programming Language » Golang » Loops in Golang
loops-in-golang-explained

This article is based on the content of this mastering Go book

In this article we are going to cover about the loops in Go. How many type of loops Go supports.

What is a Loop?

In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached. Typically, a certain process is done, such as getting an item of data and changing it, and then some condition is checked such as whether a counter has reached a prescribed number.

Every programming language has a way of looping and Go is no exception. Go offers the for loop, which allows you to retrieve over many kinds of data types.

Go does not offer support for the while keyword. However, for loops in Go can replace while loops.

The for loop

The for loop allows you to iterate a predefined number of times, for as long as condition is valid, or according to a value that is calculated at the beginning of the for loop. Such as values include the size of a slice or an array, or the number of keys on a map. This means that most common way of accessing all the elements of an array, slice or a map is the for loop.

The simplest form of a for loop follows. A given variable takes a range of predefined values:

for i := 0; i < 10; i++{
}

Generally speaking a for loop has three sections: the first one is called the initialization, the second one is called the condition, and the last one is called the afterthought. All sections are optional

In the mention loop, the values that i will take are from 0 to 9. As soon as i reaches 10, the execution of the for loop will stop. In this case, i is a local and temporary variable, which means that after termination of the for loop, i will be garbage collected at some point and disappear. However, if i was defined outside the for loop, it will keep its value and the termination of the i loop. In this case, the value of i after the termination of the for loop will be 10 as this was the last value of i in this particular program at this particular point.

You can completely exit a for loop using the break keyword. The break keyword also allows you to create a for loop without an exit condition, such as i < 10 used in the preceding example, because the exit condition can be included in the code block of the for loop. You are also allowed to have multiple exit conditions in a for loop. Additionally, you can skip a single iteration of a for loop using the continue keyword.

The while loop

As I mentioned earlier, Go does not offer the while keyword for writing while loops but allows you to use a for loop instead of a while loop. I will present two example where a for loop does the job of a while loop.

Firstly, let’s look at a typical case where you might want to write something like while(true):

for{
}

It is the job of the developer to use the break keyword to exit this for loop.

However, the for loop can also emulate a do…while loop, which can be found in other programming languages.

As an example, the following Go code is equivalent to a do…while(expression) loop:

for ok := true; ok; ok = expression {
}

As soon as the ok variable has the false value, the for loop will terminate.

There is also a for condition {} loop in Go where you specify the condition and the for loop is executed for as long as the condition is true.

The range keyword

Go also offers the range keyword, which is used in for loops and allows you to write easy-to-understand code for iterating over supported Go data types including Go channels. The main advantage of the range keyword is that you do not need to know the cardinality of a slice, a map, or a channel in order to process its elements one by one.

An example with multiple Go loops

package main

import (
    "fmt"
)

func main() {

    // continue and break keyword uses
    for i := 0; i < 100; i++ {
        if i%2 == 0 {
            continue
        }
        if i == 95 {
            break
        }
        fmt.Print(i, " ")
    }
    fmt.Println()

    // this code emulates a typical while loop.
    i := 10
    for {
        if i <= 0 {
            break
        }
        fmt.Print(i, " ")
        i--
    }
    fmt.Println()

    // this loop do the job of a do...while loop
    i = 1
    expression := true
    for ok := true; ok; ok = expression {
        if i >= 10 {
            expression = false
        }
        fmt.Print(i, " ")
        i++
    }
    fmt.Println()

    // range keyword example with index and value
    anArr := [5]int{15, 4, 6, 18, 75}
    for i, value := range anArr {
        fmt.Println("index:", i, "value: ", value)
    }
    fmt.Println()

    // range keyword example with only index
    for i := range anArr {
        fmt.Println("index:", i, "value: ", anArr[i])
    }

}

The first loop shows a typical for loop, as well as the use of continue and break keywords.

The second loop code emulates a typical while loop. Note the use of the break keyword to exit the for loop.

In the third loop you can see the use of a for loop that does the job of a do…while loop. Notice that this for loop is difficult to read

In the last fourth loop we applying the range keyword to an array variable returns two values: an array index and the value of the element at that index, respectively.

You can use both of them, one of them, or none of them in case you just want to count the elements of the array or perform some other task the same number of times as there are items in an array same as we did in last loop

Executing the program will produce the following output:

$ go run main.go
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 
10 9 8 7 6 5 4 3 2 1 
1 2 3 4 5 6 7 8 9 10 
index: 0 value:  15
index: 1 value:  4
index: 2 value:  6
index: 3 value:  18
index: 4 value:  75

index: 0 value:  15
index: 1 value:  4
index: 2 value:  6
index: 3 value:  18
index: 4 value:  75

Conclusion

In this article we learned about loops how a single loop can be used in a multiple ways and other tricks of loops as well

This article is based on the content of this mastering Go book

your comments are appreciated and if you wants to see your articles on this platform then please shoot a mail at this address kusingh@programmingeeksclub.com

Thanks for reading 🙂

Join Our Newsletter!

Join our newsletter to get our latest ebook "Ultimate JavaScript Cheat-Sheet", and Tips, Articles..

We don’t spam! Read our privacy policy for more info.

Join Our Newsletter!

Join our newsletter to get our latest ebook "Ultimate JavaScript Cheat-Sheet", and Tips, Articles..

We don’t spam! Read our privacy policy for more info.

Leave a Comment

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.