Skip to the content.

Working with loops

This chapter covers working with loops in Go. Loops are used to repeat statements in your code.

Introduction

This chapter will cover:

The case for looping statements

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 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:

The for loop

The conventional for-loop has three different parts:

Repeat until the condition is met with while

A simplified version of this loop can omit the initialization and increment steps. 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
}

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")

An example run of the program could look like so:

Type command: test
Type command: something
Type command: quit
program exit

Using for-each over a range

For this next loop construct, the idea is to operate over an array or known sequence. For each iteration you can get the index 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)
 }

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 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

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:

Assignment - create a command line loop

When creating console apps, you often want to read user input. The user input could be data used in the program or it can be the user typing a command to do something like “save”, “print”, “backup” etc. We will build a program for the latter case.

  1. Create a file main.go and give it the following content:

    package main
    
    import "fmt"
    
    func main() {
       
    }
    
  2. Add the following code to the main() method:

    var keepGoing = true
    answer := ""
    for keepGoing {
      fmt.Println("Type command: ")
      fmt.Scan(&answer)
      if answer == "quit" {
        keepGoing = false
      }
    }
    fmt.Println("program exit")
    
  3. Run the code by typing go run main.go:

    go run main.go
    

    You should see an output like so:

    Type command: command
    Type command: quit
    program exit 
    

🚀 Challenge

Solution

package main

import "fmt"

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