go / beginner
Snippet
Range: Iterating Over Collections
The range keyword provides a way to iterate over elements of slices, arrays, maps, and strings. For slices and arrays, it returns the index and value. For maps, it returns the key and value. For strings, it returns the byte index and the Unicode code point. If you only need one value, you can ignore the other with the blank identifier underscore.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package mainimport "fmt"func main() {fruits := []string{"apple", "banana", "cherry"}for index, fruit := range fruits {fmt.Printf("%d: %s\n", index, fruit)}capitals := map[string]string{"Germany": "Berlin","France": "Paris",}for country, capital := range capitals {fmt.Printf("%s -> %s\n", country, capital)}for i, char := range "Hello" {fmt.Printf("%d: %c\n", i, char)}}
Breakdown
1
for index, fruit := range fruits
Iterates slice, index=0,1,2; fruit="apple","banana","cherry"
2
for country, capital := range capitals
Iterates map, order is random each run
3
for i, char := range "Hello"
Iterates string bytes, i=0,1,2,3,4; char='H','e','l','l','o'
4
_ , fruit := range fruits
Blank identifier ignores the index