0
0
GoHow-ToBeginner · 3 min read

How to Iterate Over Map in Go: Syntax and Examples

In Go, you iterate over a map using the for loop combined with the range keyword. This lets you access each key and value pair in the map easily. Use for key, value := range mapName to loop through all entries.
📐

Syntax

To iterate over a map in Go, use a for loop with range. The syntax is:

  • key: variable to hold the current key.
  • value: variable to hold the current value.
  • mapName: the map you want to loop through.

This loop runs once for each key-value pair in the map.

go
for key, value := range mapName {
    // use key and value
}
💻

Example

This example shows how to create a map of fruits and their colors, then print each fruit with its color by iterating over the map.

go
package main

import "fmt"

func main() {
    fruits := map[string]string{
        "apple":  "red",
        "banana": "yellow",
        "grape":  "purple",
    }

    for fruit, color := range fruits {
        fmt.Printf("%s is %s\n", fruit, color)
    }
}
Output
apple is red banana is yellow grape is purple
⚠️

Common Pitfalls

One common mistake is assuming the map iteration order is fixed. In Go, map iteration order is random and can change each run. Do not rely on the order of keys when looping.

Another mistake is ignoring the value when you only need the key, or vice versa. You can use _ to ignore unwanted variables.

go
package main

import "fmt"

func main() {
    numbers := map[int]string{
        1: "one",
        2: "two",
        3: "three",
    }

    // Wrong: ignoring key and value
    // for range numbers {
    //     fmt.Println("This won't compile")
    // }

    // Correct: ignore value if not needed
    for key := range numbers {
        fmt.Println("Key:", key)
    }

    // Correct: ignore key if not needed
    for _, value := range numbers {
        fmt.Println("Value:", value)
    }
}
Output
Key: 1 Key: 2 Key: 3 Value: one Value: two Value: three
📊

Quick Reference

Remember these tips when iterating over maps in Go:

  • Use for key, value := range mapName to loop.
  • Map iteration order is random and should not be relied on.
  • Use _ to ignore keys or values you don't need.
  • Maps can be of any key and value types.

Key Takeaways

Use for key, value := range mapName to iterate over all map entries in Go.
Map iteration order is random and changes each run; do not rely on it.
Use _ to ignore keys or values if you only need one part of the pair.
Maps can hold any type of keys and values, and iteration works the same way.
Always declare key and value variables in the for-range loop to access map data.