How to Use For Range Loop in Go: Simple Guide
In Go, use the
for range loop to iterate over elements in arrays, slices, maps, or strings. It returns the index (or key) and value for each item, making it easy to process collections.Syntax
The for range loop has this basic form:
for index, value := range collection {
// use index and value
}Here, collection can be an array, slice, map, or string. index is the position or key, and value is the element at that position.
You can omit index or value by using an underscore _ if you don't need them.
go
for index, value := range collection { // code using index and value }
Example
This example shows how to use for range to loop over a slice of fruits and print each index and fruit name.
go
package main import "fmt" func main() { fruits := []string{"apple", "banana", "cherry"} for i, fruit := range fruits { fmt.Printf("Index: %d, Fruit: %s\n", i, fruit) } }
Output
Index: 0, Fruit: apple
Index: 1, Fruit: banana
Index: 2, Fruit: cherry
Common Pitfalls
- Forgetting to use the underscore
_when you want to ignore the index or value causes unused variable errors. - Modifying the loop variable inside the loop does not change the original collection.
- When ranging over a map, the order of iteration is random, so do not rely on order.
go
package main import "fmt" func main() { nums := []int{10, 20, 30} // Wrong: unused index causes error // for i, num := range nums { // fmt.Println(num) // } // Correct: ignore index with _ for _, num := range nums { fmt.Println(num) } }
Output
10
20
30
Quick Reference
Use this quick guide when working with for range loops:
- Arrays/Slices:
for i, v := range slice - Maps:
for key, val := range map - Strings:
for i, ch := range str(ch is a rune) - Use
_to ignore index or value if not needed - Map iteration order is random
Key Takeaways
Use
for range to loop over arrays, slices, maps, and strings easily.The loop returns index (or key) and value for each element.
Use underscore
_ to ignore unwanted values and avoid errors.Map iteration order is random; do not rely on it.
Modifying loop variables does not change the original collection.