DEV Community

Cover image for Go from the beginning - working with loops
Chris Noring for Microsoft Azure

Posted on • Updated on

Go from the beginning - working with loops

Go from the beginning - working with loops

TLDR; this article covers working with loops in Go

You are likely to want to repeat a set of instructions. For example, you might have a list of orders where you need to process each order. Or you have a file that you need to read it line by line or there might be some other calculation. Regardless of your situation, you are likely to need a looping construct, so what are your options in Go?

You are using the for loop. There are three major ways you can use it:

  • increment steps. With the help of a variable, you define a start point, a condition when to stop and an incrementation step. This is your "classic" for-loop. Here's what it looks like:
   for i := 0; i < 10; i++ {
     // run these statements
   } 
Enter fullscreen mode Exit fullscreen mode
  • while. In many programming languages you, a have a while keyword. Go doesn't have that, but what you can do is to use the for-loop in a similar way. You omit the initialization step and increment step and get this code:
  for <condition> {
    // run these statements
  }
Enter fullscreen mode Exit fullscreen mode
  • for each. lastly, you have the for-each like construct that operates on an array like sequence. It uses the range keyword to function:
   for i,s := range array {
     // run these statements
   }
Enter fullscreen mode Exit fullscreen mode

Series

The for loop

The conventional for-loop has three distinct parts:

  • initialization, here you want to create a variable and assign it a starter value like so:
   for i:= 0;
Enter fullscreen mode Exit fullscreen mode

Note the use of ;, you usually don's use semicolon, but for this construct, you need it.

  • condition. The next step is evaluating whether you should continue incrementing or not. You define a boolean expression here, that if true, continues to loop:
   for i := 0; i< 10     
Enter fullscreen mode Exit fullscreen mode

i < 10, as long as a value is between 0 and 10 (becomes 10, then loop breaks), then it returns true and the loop continues.

  • increment, in this step, the loop variable i is updated, updating it by 1 is common but you can add any increment size, negative or positive.
   for i := 0; i< 10; i++ {

   }
Enter fullscreen mode Exit fullscreen mode

Here, i is updated by 1. This loop will run ten times.

Repeat until condition is met with while

A simplified version of this loop can omit the initialization and increment step. You are then left with the condition step only. This step tests whether a variable is true or false and the loop exits on false. Here's an example:

i := 1
for i < 10 {
  i++
  // do something
}
Enter fullscreen mode Exit fullscreen mode

In this case, we are declaring i outside of the loop. Within the loop, we need to change the value to something that will make the loop expression evaluate to false or it will loop forever.

Here's another code, using the same idea, but this time we ask for input from the user:

var keepGoing = true
 answer := ""
 for keepGoing {
  fmt.Println("Type command: ")
  fmt.Scan(&answer)
  if answer == "quit" {
   keepGoing = false
  }
 }
 fmt.Println("program exit")
Enter fullscreen mode Exit fullscreen mode

An example run of the program could look like so:

Type command: test
Type command: something
Type command: quit
program exit
Enter fullscreen mode Exit fullscreen mode

Using for each over a range

For this next loop construct, the idea is to operate over an array or some kind of known sequence. For each iteration you are able to get the index as as well as the next item in the loop. Here's some example code:

arr := []string{"arg1", "arg2", "arg3"}
 for i, s := range arr {
  fmt.Printf("index: %d, item: %s \n", i, s)
 }
Enter fullscreen mode Exit fullscreen mode

arr is defined as an array and then the range construct is used to loop over the array. For each iteration, the current index is being assigned to i and the array item is assigned to s. An output of the above code will look like so:

index: 0, item: arg1
index: 1, item: arg2
index: 2, item: arg3
Enter fullscreen mode Exit fullscreen mode

 Iterating over maps

Maps is a fundamental data structure. You can use range to iterate over maps like so:

kvs := map[string]string{"a": "apple", "b": "banana"}
for k, v := range kvs {
    fmt.Printf("%s -> %s\n", k, v)
}
Enter fullscreen mode Exit fullscreen mode

Thank you jonasbn for pointing this out

Controlling the loop with continue and break

So far, you've seen three ways you can use the for construct. There are also ways to control the loop. You can control the loop with the following keywords:

  • break, this will exit the loop construct
   arr = []int{-1,2}
   for i := 0; i< 2; i++ {
     fmt.Println(arr[i])
     if arr[i] < 0 {
       break;
     }
   }     
Enter fullscreen mode Exit fullscreen mode

The output will be:

   -1
Enter fullscreen mode Exit fullscreen mode

it won't output 2 as the loop exits after the first iteration.

  • continue, this will move on to the next iteration. If break exits the loop, continue skips the current iteration:
   arr = []int{-1,2,-1, 3}
   for i := 0; i< 4; i++ {
     if arr[i] < 0 {
       break;
     }
     fmt.Println(arr[i])
   } 
Enter fullscreen mode Exit fullscreen mode

The output will be:

   2
   3
Enter fullscreen mode Exit fullscreen mode

Summary

You've learned that there's a for-loop. You can use a for-loop when you want to repeat a set of instructions. There are three approaches you can use in Go that this article just covered.

Top comments (2)

Collapse
 
jonasbn profile image
Jonas Brømsø

Hi @softchris

Nice write up, I do not know if you skipped it deliberately, but I find the iteration over maps quite essential for programming Go and I believe it qualifies for a mention, with maps being an fundamental data type.

kvs := map[string]string{"a": "apple", "b": "banana"}
for k, v := range kvs {
    fmt.Printf("%s -> %s\n", k, v)
}
Enter fullscreen mode Exit fullscreen mode

Example lifted from Go By Example: Range

Will keep reading, so keep it up

Collapse
 
softchris profile image
Chris Noring

Thank you, I've added your example above.