Go Lesson 17 – Range Keyword | Dataplexa

The range Keyword in Go

The range keyword in Go is used to iterate over elements in data structures such as arrays, slices, maps, and strings. It provides a clean and readable way to loop through data.

Instead of manually managing indexes, range automatically returns values during iteration, reducing errors and improving clarity.


Why Use range?

Using range makes loops:

  • Easier to read
  • Less error-prone
  • More expressive for collections
  • Cleaner than traditional index-based loops

Using range with Slices

When iterating over a slice, range returns two values: the index and the element value.

package main

import "fmt"

func main() {
    marks := []int{78, 85, 90, 66}

    for index, value := range marks {
        fmt.Println("Index:", index, "Value:", value)
    }
}

Here, each student's score is accessed along with its position.


Ignoring the Index or Value

If you don’t need one of the returned values, you can ignore it using the blank identifier _.

package main

import "fmt"

func main() {
    prices := []int{1200, 850, 430}

    for _, price := range prices {
        fmt.Println("Price:", price)
    }
}

This loop focuses only on values and ignores indexes.


Using range with Arrays

Arrays behave similarly to slices when using range.

package main

import "fmt"

func main() {
    temperatures := [5]int{30, 32, 31, 29, 28}

    for i, temp := range temperatures {
        fmt.Println("Day", i+1, "Temperature:", temp)
    }
}

Each array element is accessed without manually tracking indexes.


Using range with Maps

When iterating over a map, range returns the key and the value.

package main

import "fmt"

func main() {
    salaries := map[string]int{
        "Alice": 50000,
        "Bob":   62000,
        "John":  58000,
    }

    for name, salary := range salaries {
        fmt.Println(name, "earns", salary)
    }
}

The order of iteration is not guaranteed when ranging over maps.


Using range with Strings

When used with strings, range iterates over Unicode characters instead of raw bytes.

package main

import "fmt"

func main() {
    word := "GoLang"

    for index, char := range word {
        fmt.Printf("Index %d: %c\n", index, char)
    }
}

This ensures correct handling of multi-byte characters.


Using range to Calculate Totals

A common real-world use of range is aggregating values.

package main

import "fmt"

func main() {
    expenses := []int{1200, 800, 450, 1050}
    total := 0

    for _, amount := range expenses {
        total += amount
    }

    fmt.Println("Total Expenses:", total)
}

This example calculates total monthly expenses.


range vs Traditional for Loop

Traditional loop:

for i := 0; i < len(data); i++ {
    fmt.Println(data[i])
}

Using range:

for _, value := range data {
    fmt.Println(value)
}

The range version is cleaner and safer.


Common Mistakes with range

  • Assuming maps iterate in order
  • Modifying map structure during iteration
  • Ignoring returned values unintentionally

When to Use range

  • Iterating over collections
  • Processing real-world datasets
  • Summing values or counts
  • Reading map-based records

What’s Next?

In the next lesson, you will learn about Functions in Go, including function declaration, parameters, and return values.