range

for ... range clause can be used to iterate 5 types of variables: array, slice, string, map and channel, and the following sheet gives a summary of the items of for ... range loops:
































Type 1st item 2nd item
Array index value
Slice index value
String index (rune) value (rune)
Map key value
Channel value

For array, slice, string and map, if you don’t care about the second item, you can omit it. E.g.:

  1. package main
  2. import "fmt"
  3. func main() {
  4. m := map[string]struct{} {
  5. "alpha": struct{}{},
  6. "beta": struct{}{},
  7. }
  8. for k := range m {
  9. fmt.Println(k)
  10. }
  11. }

The running result is like this:

  1. alpha
  2. beta

Likewise, if the program doesn’t need the first item, a blank identifier should occupy the position:

  1. package main
  2. import "fmt"
  3. func main() {
  4. for _, v := range []int{1, 2, 3} {
  5. fmt.Println(v)
  6. }
  7. }

The output is:

  1. 1
  2. 2
  3. 3

For channel type, the close operation can cause for ... range loop exit. See the following code:

  1. package main
  2. import "fmt"
  3. func main() {
  4. ch := make(chan int)
  5. go func(chan int) {
  6. for _, v := range []int{1, 2} {
  7. ch <- v
  8. }
  9. close(ch)
  10. }(ch)
  11. for v := range ch {
  12. fmt.Println(v)
  13. }
  14. fmt.Println("The channel is closed.")
  15. }

Check the outcome:

  1. 1
  2. 2
  3. The channel is closed.

We can see close(ch) statement in another goroutine make the loop in main goroutine end.