Close this search box.

Golang: Getting loopy with loops

The simplest form of for loop in Golang is a while loop. What?! Yep, it’s true! In Golang, there are only for loops but they double as while loops. In the below, we have a variable called i which is initially set to be equal to 1; when we call our loop we say, keep looping through while I is less than 5. You can see on the terminal output, it’s printed numbers 1 to 4 and has indeed stopped when it hits 5.

This image has an empty alt attribute; its file name is image-92.png

Now, let’s say we have a slice. That slice is like this: a := []string{“Claude”, “Sam”, “Bob”, “Claire”, “Helen”}, it has five items within it. We can easily write a loop which follows this structure: for index, value := range array_name {, here we take i (i.e. the index of the item in the slice) and then a variable name and that is set to being equal to the range of the slice.

Think of it like a Python loop, if we had the below, you can see it’s directly comparable to the screenshot of Golang code.
a = [‘Claude’, ‘Sam’, ‘Bob’, ‘Claire’, ‘Helen’]
for name in a:

Iterating over a map is slightly different. We just replace i with the word key for key, value := range map_name {.

Now, let’s look at how we would nest loops. In the below, we simply define two loops, one nested inside the other. We can then in this very strange example, print the indexs of the slices and the value within each slice.

I hope that has been useful as a quick guide with some examples into loops.

Share the Post:

Related Posts