Go – Loops Overview
Estimated reading: 3 minutes 27 views

🔄 Go Range Loop – Iterate Over Slices, Maps, Strings, and Channels (2025 Guide)

🧲 Introduction – What Is the range Keyword in Go?

The range keyword in Go is used with for loops to iterate over collections like arrays, slices, maps, strings, and channels. It simplifies looping by automatically handling indexes, keys, and values, making your code cleaner and more readable.

🎯 In this section, you’ll learn:

  • How range works with different Go data types
  • When to use index/value pairs or ignore unused values
  • Real-world examples with arrays, maps, strings, and channels
  • Tips for avoiding common mistakes

✅ Basic Syntax – for range in Go

for index, value := range collection {
    // use index and value
}

You can also discard the index or value using _.


🔢 Iterate Over Slice or Array

nums := []int{10, 20, 30}

for i, val := range nums {
    fmt.Printf("Index %d → Value %d\n", i, val)
}

📤 Output:

Index 0 → Value 10  
Index 1 → Value 20  
Index 2 → Value 30

🧹 Ignore Unused Index or Value

// Ignore index
for _, val := range nums {
    fmt.Println(val)
}

// Ignore value
for i, _ := range nums {
    fmt.Println("Index:", i)
}

🗺️ Iterate Over a Map

m := map[string]int{"a": 1, "b": 2}

for key, val := range m {
    fmt.Printf("%s → %d\n", key, val)
}

📤 Output (order not guaranteed):

a → 1  
b → 2

✅ Map iteration order is not deterministic.


🔠 Iterate Over a String (Rune by Rune)

for i, ch := range "Go💡" {
    fmt.Printf("Byte Index %d → Rune %c\n", i, ch)
}

📤 Output:

Byte Index 0 → Rune G  
Byte Index 1 → Rune o  
Byte Index 2 → Rune 💡

✅ Handles Unicode properly. Each iteration gives the byte index and the Unicode character (rune).


📬 Iterate Over Channels (until closed)

ch := make(chan int)

go func() {
    for i := 1; i <= 3; i++ {
        ch <- i
    }
    close(ch)
}()

for val := range ch {
    fmt.Println(val)
}

📤 Output:

1  
2  
3

✅ Use range to read from a channel until it’s closed.


⚠️ Common Pitfalls

MistakeFix
Expecting map order to be consistentGo maps are unordered
Forgetting to close channelrange on channels blocks until closed
Overwriting loop variable referenceAvoid capturing loop vars in goroutines

🧠 Best Practices

  • ✅ Use range for idiomatic iteration over slices, maps, strings, and channels
  • ✅ Use _ for unused values
  • ✅ Close channels if you range over them
  • 🚫 Don’t rely on map iteration order
  • ✅ Loop safely with Unicode strings using range

📌 Summary – Recap & Next Steps

The range keyword in Go provides a powerful, concise, and idiomatic way to iterate over many built-in data types. It simplifies looping logic, especially when working with collections.

🔍 Key Takeaways:

  • range is used in for loops to iterate over slices, arrays, maps, strings, and channels
  • It returns one or two values depending on the type: index/key and value
  • Use _ to discard values you don’t need
  • range works Unicode-safe with strings and channels until closed

⚙️ Next: Learn about Go Functions to build reusable logic blocks in your Go programs.


❓ FAQs – Go Range Loop

❓ What does range return for slices and arrays?
✅ It returns the index and value of each element.

❓ Does range work with strings containing emojis or Unicode?
✅ Yes. range returns each Unicode rune with its byte index.

❓ Is the order of map iteration predictable in Go?
✅ No. Go intentionally randomizes map iteration for safety and consistency.

❓ Can I use range on a channel?
✅ Yes. It reads from the channel until it’s closed.

❓ What happens if I don’t close a channel used in range?
✅ The loop will block and never exit, causing a deadlock.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Go Range Loop

Or Copy Link

CONTENTS
Scroll to Top