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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA