capypad
0 day streak
go / beginner
Snippet

Range: Iterating Over Collections

The range keyword provides a clean way to iterate over slices, arrays, maps, and channels. For slices and arrays, it returns both the index and the value. For maps, it returns the key and value. You can ignore unwanted values using the blank identifier _.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main
import "fmt"
 
func main() {
colors := []string{"Red", "Green", "Blue"}
 
for index, value := range colors {
fmt.Printf("%d: %s\n", index, value)
}
 
ages := map[string]int{"Max": 25, "Anna": 30}
for name, age := range ages {
fmt.Println(name, "is", age)
}
}
Breakdown
1
for index, value := range colors {
Range returns index and copy of each element
2
fmt.Printf("%d: %s\n", index, value)
Prints formatted output with index and value
3
for name, age := range ages {
Range over map returns key and value pairs
4
_ = index
Blank identifier discards unwanted index