for-range loop in Golang with Example

for-range loop in Golang with Example

in this post, we’ll learn how to use for-range loop in different ways using live examples. The for is used to traverse over elements of data structures slice, array, map, string etc.

The for statement also has a variant that iterates across an expression that evaluates to an array, slice, map, string, or channel using the keyword range.

Syntax:

The basic syntax for a for-range loop is:

for index, value := range anyDS {
fmt.Println(value)
}
  • index : This contains index of the value.
  • value : The value, which have on each iteration.
  • anyDS : The values of this data structure will be accessed in the loop.

Range Iterating over a For Loop

The for-range loop can be used to access individual key-value pairs in a map. Let’s see the below example:

package main
import "fmt"

func main() {

        // Array of employee ages
    ages := [3]int{32, 28, 55}
        
    for i, age := range ages {
 
        // Prints aged
        fmt.Printf("Array index %d and value is = %d \n", i, age)
    }
}

Output:

Array index 0 and value is = 32
Array index 1 and value is = 28
Array index 2 and value is = 55

Range Iterating over a map

The for-range loop can be used to access individual key-value pairs in a map. Let’s see the below example:

package main
import "fmt"

func main() {

        emp_age_map := map[string]int{"Adam": 32,
                           "Joe": 28, "Sam": 55}
 
    // Printing maps using key-value pair
    for emp_name, age := range emp_age_map {
        fmt.Println("Age of", emp_name, "is: ", age)
    }
}

Output:

Age of Adam is: 32
Age of Joe is: 28
Age of Sam is: 55

Range over String in Golang

Let’s use range-for on the string.

package main
import "fmt"

func main() {

        for i, item := range "golanglearn" {
                fmt.Printf("string[%d] = %#U\n", i, item)
        }
}

Output:

string[0] = U+0067 'g'
string[1] = U+006F 'o'
string[2] = U+006C 'l'
string[3] = U+0061 'a'
string[4] = U+006E 'n'
string[5] = U+0067 'g'
string[6] = U+006C 'l'
string[7] = U+0065 'e'
string[8] = U+0061 'a'
string[9] = U+0072 'r'
string[10] = U+006E 'n'