golang

Golang For Loop

Loops are one of the most critical features in programming. Using loops, you can repeatedly execute a block of code without re-writing it over and over. Loops help to reduce errors in code and improve readability by removing the need to duplicate a piece of code multiple times in the same program.

This guide will teach us how to work with loops in the go programming language.

Introduction

Unlike other programming languages that feature over one loop constructs such as while and make loops, Go provides one loop construct: the for loop.

Although it may seem limited, we can extend the for loop to perform other loop operations such as infinite loops, iterating over items, while loops, and more.

Using a single loop construct allows you to maintain clean and readable code without worry what loop constructs to use for a specific operation.

Go For Loop

Let us discuss how to work with the for loop in go. We classify a for loop as an iteration statement. This means a for loop allows you to repeatedly execute a block of code for the specified number of times.

For example, you can run print something x number of times or read the process a specific number of times.

The syntax of a for loop in go is as shown:

for[init]; [condition]; [post] {
    // loop operation
}

The above example uses the classic for loop syntax. We start by defining an initial statement followed by the loop condition, and finally a post statement or an increment or decrement operation.

Let us take an example to print values from 1 to 10. We can create a simple for loop as:

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

   fmt.Println(i)

}

Let us dissect parts of the for loop above.

We start by declaring the initial statement. In our example, we declare a variable called i and assign its initial value as 0.

The next part is the loop condition. This defines the condition to check and, if true, keep executing the code inside the for a loop until false. In our example, we check if the value of i is less than or equal to 10.

The final part is the post states. This defines the action to be performed after each iteration of the loop. In our example, we increase the value of i by one using the increment operator (++).

The full code snippet is as shown:

package main

import"fmt"

funcmain() {
    print_ten()
}
funcprint_ten() {
    fori := 0; i<= 10; i++ {
        fmt.Println(i)
    }
}

Once we run the above code, we should see the program print numbers from 1 to 10 as:

$ go run for_loop.go

0

1

--- output truncated---

9

10

The loop executes 10 times, where each iteration increases the value of i by 1. This continues until the value of i is not less than 10. Once the condition is false, the loop exits.

NOTE: You are not limited to setting the initial statement to 0. You can set any desired range of values. For example, we can create a for loop to print the even numbers between 20 and 50 using a for loop as shown:

    fori := 20; i<50; i++ {
        ifi%2 == 0 {
            fmt.Println(i)

        }
    }

In the example above, we set the initial value as 20 and a loop condition (if the value of i is less than 50). We then take the value of i and pass it to an if statement. If i mod 2 is equal to 0, then print i.

The above code prints the even numbers in the range of 20 and 50.

$ go run for_loop.go

20

22

--- code truncated ---

46

48

Keep in mind that you can set any operation as the post statement as long as it changes the value of the initial statement per each iteration.

For example:

funcmodify_interval() {
    fori := 0; i<100; i += 5 {
        fmt.Println(i)
    }
}

In the example above, we increment the value of i by 5 per each loop iteration.

NOTE: You can also use a decrement operation as the post statement.

Using a for loop as a while loop

You can create a while loop in go by using a single component of the for-loop construct. We can also refer to this method as a condition loop.

For example:

    i := 1
    fori<5 {
        fmt.Println(i)
        i++
    }

Here, we declare the initial statement outside the for-loop block. Inside the for loop, we define the condition to check if the value of i is less than 5. If true, we continue to perform the operations inside the for-loop block.

We can use the break keyword to terminate the loop when a specific condition is reached.

    for  {
        ifi == 10 {
            break  
        }
    }

Using a for loop to create an infinite loop

We can also create an infinite loop using the for-loop construct. If we skip the condition part of the for loop, we create an infinite loop as shown in the example below:

    i := 0
    for {
        i++
    }

In the example snippet above, the loop will run forever as the condition is always true.

Using For Loops to Iterate over data types

We can also use a for loop to iterate over various data types such as strings, arrays, and slices. These types of loops are also known as for-range loops.

For example, the code below iterates over an array:

    databases := []string{"MongoDB", "SQL Server", "SQLite", "CockroachDB", "Fauna DB"}
    fori := 0; i<len(databases); i++ {
        fmt.Println(databases[i])
    }

If i is less than the length of the array, print each item in the array and increase the value of i.

If we run the code above, we should get an output as shown:

$ go run for_loop.go
MongoDB
SQL Server
SQLite
CockroachDB
Fauna DB

Here, we print each item from the array.

We can also iterate over maps, as shown in the example below:

    my_map := map[string]string{
        "id":     "1",
        "name":   "Jonh Doe",
        "salary": "$150000",
    }
    for key, value := range my_map {
        fmt.Println(key, value)
    }

In this example, we iterate over each key and its associated value of the map. The code above should return the output as:

$ go run for_loop.go

salary $150000

id 1

name Jonh Doe

Closing

This guide explored the basics of working with loops in the go programming language. Using loops, you can repeatedly execute a set of instructions without duplicating the code.

Thanks for reading, and stay tuned for more go tutorials.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list