Posted on Leave a comment

Loops in Go

Loops in Go

There is only one keyword to perform loops in Go: for. The implementation is very flexible. In this article, we’ll consider the various ways to use it. If you’re interested in the details, you should definitely go through the official specification.

For loops in Go

First, let’s see how to replicate the common C-style for loop. In Go, it works similar to other languages. We supply 3 statements after the keyword. The first is an initial statement to run, the second is the condition that is evaluated before each iteration and the third is run at the end of an iteration.

package main

import "fmt"

func main() {
    for i := 1; i <= 10; i++ {
        fmt.Println(i)
    }
}
1
2
3
4
5
6
7
8
9
10

While Loops in Go

In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.

In Go, we use the for keyword to write a while loop by providing only a single statement. The loop will continue to run as long as the statement is true.

package main

import "fmt"

func main() {
    var a = 1

    for a <= 5 {
        fmt.Printf("a is: %v \n", a)
        a++
    }
}
a is: 1 
a is: 2 
a is: 3 
a is: 4 
a is: 5 

The Range Clause

The range clause allows us to iterate over an array, slice, map, string, or channel.

Looping over an array using range

When we use range to loop over an array, we will receive 2 values for each iteration. The index of each element and a copy of the value. Receiving the 2nd value is optional.

package main

import "fmt"

func main() {
    var myArray = [...]int{1,2,3,4}

    for k, v := range myArray {
        fmt.Printf("index=%v, value=%v \n", k, v)
    }
}
index=0, value=1 
index=1, value=2 
index=2, value=3 
index=3, value=4 

Looping over a slice using range

Just like with an array, when we use range to loop over a slice, we will receive 2 values for each iteration. The index of each element and a copy of the value. Receiving the 2nd value is optional.

package main

import "fmt"

func main() {
    var mySlice = []int{1,2,3,4}

    for k, v := range mySlice {
        fmt.Printf("index=%v, value=%v \n", k, v)
    }
}
index=0, value=1 
index=1, value=2 
index=2, value=3 
index=3, value=4 

Looping over a map using range

As you may expect, when we loop over a map using range, we also receive 2 values. This time the values are the key of the element in the map and a copy of the value. Receiving the 2nd value is optional.

package main

import "fmt"

func main() {
    var myMap = map[string]string{
        "foo": "bar",
        "boo": "baz",
    }

    for k, v := range myMap {
        fmt.Printf("key=%v, value=%v \n", k, v)
    }
}
key=foo, value=bar 
key=boo, value=baz

Looping over a string using range

When we loop over a string using range, we also receive 2 values in each iteration. The first value is the byte position where the character begins, the second value is a rune which represents a single Unicode character. As usual, receiving the 2nd value is optional.

package main

import "fmt"

func main() {
    var myString = "Stephen"

    for index, runeValue := range myString {
        fmt.Printf("%#U starts at byte position %d\n", runeValue, index)
    }
}
U+0053 'S' starts at byte position 0
U+0074 't' starts at byte position 1
U+0065 'e' starts at byte position 2
U+0070 'p' starts at byte position 3
U+0068 'h' starts at byte position 4
U+0065 'e' starts at byte position 5
U+006E 'n' starts at byte position 6

Looping over a channel using range

When we loop over a channel using range, we receive a single value, which is the next element in the channel.

package main

import "fmt"

func main() {
    queue := make(chan string, 2)
    queue <- "one"
    queue <- "two"
    close(queue)

    for elem := range queue {
        fmt.Println(elem)
    }
}
one
two

Conclusion

We’ve seen the various loop mechanics in Go. Now Go forth and prosper. 😎.

Spread the love
Posted on Leave a comment
Leave a Reply

Your email address will not be published. Required fields are marked *