Go gotcha: Unexpected values in range loop

Why does this code…

primes := []int{2, 3, 5, 7}
for p := range primes {
        fmt.Println(p)
}

…print:

0
1
2
3
Answer

For arrays and slices, the range loop generates two values:

  • first the index,
  • then the data at this position.

If you omit the second value, you get only the indices.

To print the data, use the second value instead:

primes := []int{2, 3, 5, 7}
for _, p := range primes {
        fmt.Println(p)
}

In this case, the blank identifier (underscore) is used for the return value you're not interested in.

See Range loops (for each loops) explained for all about range loops in Go.

Comments

Be the first to comment!