Golang range loop examples | For each loop tutorials

In this blog post, we will explore the use of a “for each” loop with a range in the Go language, accompanied by examples.

Golang range loop example

The for each loop in Go is essentially a for loop that utilizes the range keyword. It is employed to iterate through each element (key/index and value) of various data structures, such as Arrays, Slices, Maps, and Strings.

This type of loop proves beneficial when there’s a need to iterate through the elements of a data structure without explicitly determining its length.

The syntax for the for each range loop is as follows:

for key, value := range collection{
// body
}

During the iteration of a collection, each iteration involves a key or index and a corresponding value or element at that index.

Here are some key points to note about the for range loop.

  • This construct is employed to iterate through elements of collection types.
  • Each iteration’s data comprises two components: a key or index and a value or element at that index.
  • The order of iterated elements is not guaranteed to be preserved in collections.
  • Use the underscore (_) as a placeholder for the key when you only need the values during array iteration.
  • For arrays and slices, in each iteration, the first element is an index, and the second element is the value or element at that index position. If the array or slice is empty, the loop returns nothing.

For each array range iteration example

Create an array of numbers iterate through them, and print the index and value to the console using Printf.

package main

import "fmt"

func main() {

    // Array of numbers
    numbers := [3]int{6, 9, 3}
    // Iterate numeric array
    for key, value := range numbers {
        fmt.Printf("%d = %d\n", key, value)
    }
}

Output:

0 = 6
1 = 9
2 = 3

If you don’t need the index value, you can use ’_’ to skip the index. Only the value is printed to the console.

func main() {
    // Iterate numeric array
    numbers := [3]int{6, 9, 3}
    for _, value := range numbers {
        fmt.Printf("%d ", value)
    }
}

Output is

6 9 3

Alternatively, you can iterate solely with the index. By using the index, you have direct access to the corresponding value through array[index].

func main() {
    // Iterate numeric array
    numbers := [3]int{6, 9, 3}
    for i := range numbers {
        fmt.Printf("%d ", numbers[i])
    }
}

Output:

6 9 3

Loop Range through collection example

The below example covers the following things

  • Iterating through elements in a Numeric Array
  • Looping through elements in a String Array
  • Iterating through elements in Unicode characters of a string
  • Iterating through elements in a Map
package main

import "fmt"

func main() {

    // Create Numeric array
    numbers := [3]int{6, 9, 3}
    // Iterate numeric array
    for key, value := range numbers {
        fmt.Printf("%d = %d\n", key, value)
    }
    // Create String array
    strs := [3]string{"one", "two", "three"}
    // Iterate String array
    for key, value := range strs {
        fmt.Printf("%d = %s\n", key, value)
    }

    /* create a map*/
    emps := map[string]string{"1": "John", "2": "Franc", "3": "Kiran"}

    /* Iterate map using keys*/
    for emp := range emps {
        fmt.Println("Emp Id: ", emp, " Name: ", emps[emp])
    }
    /* Iterate Unicode characters of a String*/
    for index, character := range "本語日" {
        fmt.Printf("%#U  position %d\n", character, index)
    }

}

The output of the above program code is

0 = 6
1 = 9
2 = 3
0 = one
1 = two
2 = three
Emp Id:  1  Name:  John
Emp Id:  2  Name:  Franc
Emp Id:  3  Name:  Kiran
U+672C ''  position 0
U+8A9E ''  position 3
U+65E5 ''  position 6

Summary

To summarize, this tutorial has covered the Go for range loop and explained multiple examples illustrating its application in iterating through different objects, including maps, arrays, and slices.