dousao6260 2014-10-23 11:19 采纳率: 0%
浏览 30
已采纳

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

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 怎么获取下面的: glove_word2id.json和 glove_numpy.npy 这两个文件
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug