Sling Academy
Home/Golang/Iterating Over Maps with `for range` in Go

Iterating Over Maps with `for range` in Go

Last updated: November 24, 2024

In the Go programming language, maps are often utilized to store key-value pairs and can be iterated over using the for range loop. This article will guide you through the process of iterating over maps in Go, providing code examples from basic to advanced levels to enhance your understanding.

Basic Iteration Over Maps

To begin with, let's look at the basic syntax for iterating over a map in Go. Consider the following example where we use the for range loop to retrieve and print each key-value pair stored in a map:

package main

import "fmt"

func main() {
    colors := map[string]string{
        "red":    "#FF0000",
        "green":  "#00FF00",
        "blue":   "#0000FF",
    }

    for key, value := range colors {
        fmt.Printf("%s: %s\n", key, value)
    }
}

In this example, we declare a map called colors, with color names as keys and their respective hexadecimal code as values. The for range loop iterates over the map, retrieving both the keys and values.

Intermediate Iteration with Key-only Retrieval

If you only need the keys of a map, you can ignore the values by using the blank identifier _ in the range clause. Here's how that works:

package main

import "fmt"

func main() {
    cities := map[string]int{
        "New York":   8,
        "Los Angeles": 4,
        "Chicago":      3,
    }

    for key := range cities {
        fmt.Println(key)
    }
}

In this code snippet, we iterate over the map cities to print only the keys, ignoring the population values.

Advanced Iteration with Value-only Retrieval

In some scenarios, you may only be interested in the values of a map. In such cases, you can use the blank identifier to ignore the keys:

package main

import "fmt"

func main() {
    scoreBoard := map[string]int{
        "player1": 24,
        "player2": 34,
        "player3": 18,
    }

    for _, score := range scoreBoard {
        fmt.Println(score)
    }
}

Here, we iterate over the scoreBoard map to print only the scores, ignoring the player identifiers.

Advanced Example: Iterating with Conditional Logic

Sometimes, you need to apply conditional logic during the iteration process. You can perform conditional checks on each element in the map as shown below:

package main

import "fmt"

func main() {
    languages := map[string]int{
        "Python": 1991,
        "Java":   1995,
        "Go":     2009,
    }

    for lang, year := range languages {
        if year < 2000 {
            fmt.Printf("%s is an older language.\n", lang)
        } else {
            fmt.Printf("%s is a relatively new language.\n", lang)
        }
    }
}

In this advanced example, we iterate over a map of programming languages and their release years, applying a conditional check to print whether the language is old or new.

Using these examples, you can effectively iterate over maps in Go with the for range statement and apply various logical patterns as your applications demand.

Next Article: Checking for Key Existence in Maps in Go

Previous Article: Understanding Zero Values in Maps in Go

Series: Working with Maps in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant