For statements with
range
clauseA “for” statement with a “range” clause iterates through all entries of an array, slice, string or map, values received on a channel, or integer values from zero to an upper limit [Go 1.22].
Wow, that’s a long list.
And it’s about to get longer! Go 1.23 is scheduled to add iterator functions to that list, but we’ll talk about that when the time comes (in August).
For now, let me just briefly show you an example of what each of these looks like, then we’ll continue talking about the details of how they work.
-
Range over an array or slice:
for _, x := range []int{1,2,3} { // Where list is of array or slice type fmt.Println(x) }
prints:
1 2 3
-
Range over a string
for _, x := range "Hello, 世界" { fmt.Println(string(x)) }
prints:
H e l l o , 世 界
-
Range over a map
for k, v := range map[string]string{"cow": "moo", "chicken": "cluck"} { fmt.Println(k, v) }
prints:
cow moo chicken cluck
or (because a map’s order is undefined):
chicken cluck cow moo
-
values received on a channel
ch := make(chan int, 3) ch <- 10 ch <- 20 ch <- 33 close(ch) for x := range ch { fmt.Println(x) }
prints:
10 20 30
-
integer values from zero to an upper limit (added in Go 1.22)
for x := range 5 { fmt.Println(x) }
prints:
0 1 2 3 4
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)