Loops in Golang

Author

Gurleen Sethi on 05 May 2022

Loops in Golang

Getting Started #

In this article, you are going to learn how to loop 🔁 in golang. Looping is a fairly simple concept in general as well as in golang, there are slight differences when compared to other languages and we are going to cover them in this article.

As always, I recommend you to try out all the examples by hand 👨🏻‍💻 the more you practice, the more you understand, and the more you retain. Go Playground and GoPlay are good online websites to quickly write and run some go code.

The for loop #

Go only has one type of loop, the for loop.

package main

import "fmt"

func main() {
	for i := 0; i < 5; i++ {
		fmt.Println("i:", i)
	}
}

The output of this code will be:

i: 0
i: 1
i: 2
i: 3
i: 4

In GO, there is no while or any other keyword for looping, but we can use for to mimic all kinds of behaviours.

Mimic a while loop #

Let us take the previous example and try to write it in a way you would write a while loop.

package main

import "fmt"

func main() {
	i := 0

	for i < 5 {
		fmt.Println("i:", i)
		i++
	}
}

The output for this piece of code will be the same as before.

Mimic a do-while loop #

A do-while loop is the one that runs at least once, we can re-arrange a few statements and get the desired result.

package main

import "fmt"

func main() {
	i := 0

	for { // 👈 no condition in for loop
		fmt.Println("i:", i)

		i++

		if i >= 5 {
			break // 👈 breaking out of the loop
		}
	}
}

The above loop will run at least once and produce the same output as the previous examples.

Infinite loop #

If you don't specify any condition in the for loop and do not break out of it, it will run forever.

package main

import "fmt"

func main() {
	i := 0

	for {
		fmt.Println("i:", i)
		i++
	}
}

This will run forever, you wouldn't write these kinds of loops in day-to-day applications, but you use them quite often, for example, a web server would use an infinite loop to receive requests forever. For example, somewhere deep inside the server.go file, there is an infinite loop accepting connections for ever.

Using range #

GO has another keyword used along with for that helps you range over arrays and maps, it is called range.

Using with arrays:

package main

import "fmt"

func main() {
	arr := []string{"A", "B", "C", "D"}

	for index, value := range arr {
		fmt.Printf("%d: %s\n", index, value)
	}
}

The output of this code will be:

0: A
1: B
2: C
3: D

range returns two values:

  • index: The first is the index of the array
  • value: The second is the actual value of the item in the array.

Using with maps:

package main

import "fmt"

func main() {
	myMap := map[string]int{"A": 1, "B": 2, "C": 3, "D": 4}

	for key, value := range myMap {
		fmt.Printf("%s: %d\n", key, value)
	}
}

The output of this code will be:

C: 3
D: 4
A: 1
B: 2

(Since map has no guaranteed order the output can be different when you run the above example)

range returns two values:

  • key: Key of a map item.
  • value: Value of a map item.

Loop labelling #

There are cases where you have nested loops (one loop inside the other) and you want to break out of the outer loop from the inner loop, in this case, you just using break will not work, so go provides loop labels to help you out with this,

package main

import "fmt"

func main() {
outer: // 👈 label the outer loop
	for i := 0; i < 10; i++ {
		for j := 0; j < 50; j++ {
			fmt.Printf("j: %d\n", j)
			if j == 4 {
				break outer // 👈 using the label to break out from inner loop
			}
		}
	}
}

In the above example, we have labelled the outer loop outer and used that inside the inner loop (break outer). If you were to just write break then the program would just break out of the inner loop and not the outer loop.

(Select an answer)
1. for
2. while
3. loop

Thank you for reading this article, you are well equipped to loop some things in golang now. 🎉

Table of Contents
Subscribe via email

Get notified once/twice per month when new articles are published.

Byte Byte Go Affiliate
TheDeveloperCafe
Copyright © 2022 - 2024 TheDeveloperCafe.
The Go gopher was designed by Renee French.