For-range Loop in Golang with Example

Exploring Golang’s for-range Loop with Real-world Examples

Welcome to our guide on the for-range loop in Golang! In this post, we’ll dive into live examples, demonstrating how to leverage this powerful loop to traverse elements in arrays, maps, and strings.

Understanding the Basics: for-range Loop Syntax

Let’s start with the basic syntax:

for index, value := range anyDS {
    fmt.Println(value)
}

Here, index represents the index of the value, value is the value for each iteration, and anyDS is the data structure being accessed.

Iterating over Arrays

See the for-range loop in action with an array of employee ages:

package main

import "fmt"

func main() {
    ages := [3]int{32, 28, 55}
  
    for i, age := range ages {
        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

Unlocking the Power for Maps

Explore the versatility of for-range with maps:

package main

import "fmt"

func main() {
    empAgeMap := map[string]int{"Adam": 32, "Joe": 28, "Sam": 55}
 
    for empName, age := range empAgeMap {
        fmt.Println("Age of", empName, "is: ", age)
    }
}

Output:

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

Exploring Strings with for-range

Apply the for-range loop to strings, revealing the Unicode representation of each character:

package main

import "fmt"

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

Output:

string[0] = U+0064 'd'
string[1] = U+0071 'q'
string[2] = U+0075 'u'
string[3] = U+006E 'n'
string[4] = U+0069 'i'
string[5] = U+0076 'v'
string[6] = U+0065 'e'
string[7] = U+0072 'r'
string[8] = U+0073 's'
string[9] = U+0069 'i'
string[10] = U+0074 't'
string[11] = U+0079 'y'

Check Also: