Go For Loop Example

Go For Loop, Introduction to Loops

 

Now that you’ve been introduced to flow control with if statements let’s move on to the Go for loop. The purpose of a loop is to execute a block of code some number of times or until/while some condition is true. Loops save us from needing to write the same code multiple times and make your code more adaptable. With a loop, you can put the control of your program’s execution flow into its own hands.

Most other programming languages tend to have multiple loop types, however, Go only has the for loop. Go’s designers implemented only one loop type because the Go for loop can accomplish the same purpose as other loop types. Supporting only one loop keeps the language syntax more straightforward.

At this point, you should be familiar with the standard project set up. Create a new folder in you GOPATH/src folder for our Go for loop project. I’ve called mine “forloop” and create a folder named main inside of it. In the main folder create a file named main.go that we’ll use for the code of this project.

The Go For Loop

While it’s true that Go only has one loop, the Go for loop has a few variations which allow it to fill the purposes that are accomplished by other loops in other languages. The first variation of the Go for loop that we’ll talk about is commonly referred to as the “C style” for loop. The C style for loop is the variation of the for loop most widely used by languages inspired by the C programming language.

The C style for loop has four parts, an initializer, a condition, a post-action, and a block of code to be executed each time we go through the loop. The initializer, the condition, and the post-action following the “for ” keyword. Semicolons (;) are used to separate the three parts. The code block follows the post action, it’s opening brace ({) must be on the same line and its closing brace (}) must be on a new line by itself.

1
2
3
4
5
6
7
8
9
10
11
package main

import (
    "fmt"
)

func main () {
    for i := 1; i <= 3; i++ {
        fmt.Println(i)
    }
}

The initializer is the “i := 1;” part immediately following the for keyword. This syntax should look familiar to you; we’re creating a variable named “i” and setting its value to 1. The initializer part of the Go for loop is run only once, before the first execution of the block of the for loop.

The condition is the “i <= 3;” part that comes after the initializer. The condition evaluates whether the statement is true or false. The condition is evaluated each time iteration of the loop before the execution of the block. If the condition evaluates to false, we’ll stop the loop instead of executing the block again. This condition is what controls the “loop” part of the Go for loop. We execute the block; then after execution of the block we check if the condition is true. If the condition is true, then we’ll execute the block again, then repeat until the condition is no longer true.

The post action “i++” is the last part of the Go for loop set up. The increment operator (++) takes whatever the current value of the variable it’s attached to (in this case “i”) is and increments it by one. The statement in the post action is executed after the code in the block of the for loop.

1
2
3
for i := 1; i &lt;= 3; i++ {
    fmt.Println(i)
}

So, let’s step through the execution of our for loop. First, we’ll execute the initializer and create a variable named “i” and set it’s value to be 1. Next, we evaluate our condition and check if “i” (currently 1) is less than or equal (<=) to 3, which it currently is. Then, because our condition is true, we’ll execute the block of the loop, which prints out the current value of “i” which is 1. Finally, we increment “i” by one, which now makes the value of “i” equal to 2.

Now we’ll loop, we start by checking if our condition is true, since “i” is now two it’s still true that “i” is less than or equal to 3. We’ll loop twice, incrementing “i” and printing out 2 followed by 3. After printing out 3, we’ll have incremented “i” to equal 4. Because four is not less than or equal to 3 our condition is now false, and we’ll stop looping.

Let’s Talk About Scope

Before we look at other variations of the Go for loop I think it’s a good time to talk about scope. Scope refers to the part of your program that your variable exists in and is accessible. Variables are in scope inside the block they’re created in and any blocks inside of that block. In the case of a for loop the initializer is also a part of the scope of the block of the for loop.

1
2
3
4
5
6
7
8
func main () {
    foo := "bar"
    for i := 10; i &lt; 10; i++ {
        fmt.Println(foo)
        fmt.Println(i)
    }
    fmt.Println(foo)
}

We’ve created the variable “foo” inside of our main func, it’s in scope inside of our for loop and after the for loop, because the main func block encloses the loop block. We can use the “i” variable inside of the for loop block because we created it in the loop initializer. However, we cannot use the “i” variable in the main func block outside of the for loop block as it’s now out of scope.

Conditional For Loop

You can write the Go for loop with only the condition and exclude the initializer, post statement, and the semicolon (;) separators. The conditional for loop is useful when you want to control the loop execution from inside the loop or loop until some function returns false.

1
2
3
4
5
6
7
8
9
10
11
12
package main

import (
    "fmt"
    "math/rand"
)

func main () {
    for rand.Intn(3) != 0 {
        fmt.Println("Still true!")
    }
}

The rand.Intn() function returns a (sort of) random number between 0 and the number you pass it as an argument. In this case, it generates a random number between 0 and 3. Our Go for loop has the condition that the return from our rand.Intn(3) function is not 0. The loop will print “Still true!” until rand.Intn(3) returns 0.

Break and Continue

Before talking about the last Go for loop variation, we’ll introduce the break and continue keywords. The break keyword, well, breaks your for loop. When you use the break keyword your for loop will immediately stop what it’s doing and begin executing the code after the for loop block. The continue keyword will cause your loop to stop running any more statements in the current loop iteration and start the next iteration of the loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func main () {
    for i := 0; i &lt;= 3; i++ {
        if i == 2 {
            break
        }
        fmt.Println(i)
    }
    fmt.Println()
    for i:= 0; i &lt;= 3; i++ {
        if i == 2 {
            continue
        }
        fmt.Println(i)
    }
}

The Bare For Loop

The last Go for loop that we’re going to talk about is the bare for loop. The bare for loop is a for loop that has no condition, initializer, or post action. The loop will continue until it’s broken. You’ll eventually use this version of the Go for loop extensively to run background tasks that you want to execute forever while your program runs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package main

import (
    "fmt"
    "math/rand"
)

func main () {
    fmt.Println("Starting the loop")
    for {
        if rand.Intn(5) == 3 {
            break
        } else {
            fmt.Println("Not five!")
        }
    }
    fmt.Println("The loop ended!")
}

 

Chris Sotherden

Originally a native of upstate NY, I relocated to North Carolina in 2013 where I've since helped open the new R&D headquarters for Optanix. I've been with Optanix (formerly ShoreGroup) for over ten years, where I've worked my way up from entry-level to Lead Architect. I taught myself programming in high school and am an all around technology nerd from the design of programming languages and compilers, to quantum computing, and rockets. Outside of technology I've competed in powerlifting and medium distance running, as well as smoking some mean BBQ. Oh, my partner and I also breed, show, and sell fancy goldfish!

>