I'm learning Go and having a great time so far.
The following code outputs the sum as 45
package main
import "fmt"
func main(){
//declare a slice
numSlice := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
var sum int = 0
for num := range numSlice {
sum += num
fmt.Println("num =", num)
}
fmt.Println("sum =", sum)
}
The following code, where I use _
the blank identifier to ignore the index in the for declaration outputs the sum as 55
//declare a slice
numSlice := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
var sum int = 0
for _,num := range numSlice {
sum += num
fmt.Println("num =", num)
}
fmt.Println("sum =", sum)
This has got me slightly stumped. From my understanding the blank identifier is used to ignore the slice index . But it also seems to be shifting the index and thereby ignoring the last element in the slice.
Can you please explain what's happening here and possibly why. I'm assuming this is not a bug and is by design. Go is so well designed so what would the possible use cases be for this kind of behaviour?