Go Range Loop
The range keyword iterates over collections like arrays, slices, maps, and strings without manually managing index variables. It is the idiomatic Go way to loop over data structures.
Range Over a Slice
Range returns two values on each iteration: the index and the value at that index.
package main
import "fmt"
func main() {
fruits := []string{"Apple", "Banana", "Mango"}
for index, value := range fruits {
fmt.Printf("Index %d: %s\n", index, value)
}
}
Output:
Index 0: Apple
Index 1: Banana
Index 2: Mango
Range Diagram
fruits := ["Apple", "Banana", "Mango"]
───┬─── ───┬──── ───┬───
│ │ │
index 0 index 1 index 2
for index, value := range fruits
│ │
│ └── the actual element at that position
└───────────── the position number (0, 1, 2...)
Ignoring the Index
Use _ to discard the index when only the value is needed.
package main
import "fmt"
func main() {
scores := []int{90, 85, 78, 92}
for _, score := range scores {
fmt.Println(score)
}
}
Output:
90
85
78
92
Ignoring the Value
Use only the index when the value is not needed.
package main
import "fmt"
func main() {
items := []string{"A", "B", "C"}
for i := range items {
fmt.Println("Position:", i)
}
}
Range Over a Map
Range over a map returns each key-value pair. The order is not guaranteed in maps.
package main
import "fmt"
func main() {
capitals := map[string]string{
"India": "New Delhi",
"France": "Paris",
"Japan": "Tokyo",
}
for country, capital := range capitals {
fmt.Printf("%s → %s\n", country, capital)
}
}
Output (order may vary):
India → New Delhi
France → Paris
Japan → Tokyo
Range Over a String
Ranging over a string returns each character as a rune (Unicode code point) along with its byte index.
package main
import "fmt"
func main() {
word := "Go!"
for index, char := range word {
fmt.Printf("Index %d: %c\n", index, char)
}
}
Output:
Index 0: G
Index 1: o
Index 2: !
Range Over an Integer (Go 1.22+)
Starting from Go 1.22, range can iterate directly over an integer number.
package main
import "fmt"
func main() {
for i := range 5 {
fmt.Println(i)
}
}
Output:
0
1
2
3
4
Comparison: for vs range
| Scenario | Better Choice |
|---|---|
| Loop a fixed number of times | for i := 0; i < n; i++ |
| Loop over a slice or array | for i, v := range slice |
| Loop over a map | for k, v := range map |
| Loop over characters in a string | for i, c := range str |
Key Points
rangeworks on slices, arrays, maps, strings, and channels- It returns index and value — use
_to ignore either one - Ranging over a map does not guarantee order
- Ranging over a string gives Unicode runes, not raw bytes
