dousao6260 2014-10-23 11:19 采纳率: 0%

# 为什么用_空白标识符进行范围迭代会产生不同的值

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?

• 写回答

#### 1条回答默认 最新

• 普通网友 2014-10-23 11:24
关注

Single parameter range uses indexes, not values. Because your indexes are also going up from 0 to 9 using range with a single param will add the indexes up from 0 to 9 and give you `45`

``````package main
import "fmt"

func main(){
//declare a slice
numSlice := []int{0, 0, 0, 0}
var sum int = 0

for num := range numSlice {
sum += num
fmt.Println("num =", num)
}
fmt.Println("sum =", sum)
}
``````

## Output

``````num = 0
num = 1
num = 2
num = 3
sum = 6
``````
本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

#### 悬赏问题

• ¥15 自己配的nginx 正向代理一直失败（相关搜索：谷歌浏览器|拒绝连接）