douren4075 2019-07-18 15:30
浏览 69
已采纳

分配给无类型空白标识符有什么影响?

I found the following code in crypto/sha256/sha256.go:

func putUint32(x []byte, s uint32) {
    _ = x[3]
    x[0] = byte(s >> 24)
    x[1] = byte(s >> 16)
    x[2] = byte(s >> 8)
    x[3] = byte(s)
}

All I see that this assignment to the blank identifier would do is panic if len(x) wasn't at least 4, which isn't even an effect of the assignment as much as it is of the evaluation of x[3]. So, wouldn't the following (shorter, more desirable code) be equivalent?

func putUint32(x []byte, s uint32) {
    x[3] = byte(s)
    x[2] = byte(s >> 8)
    x[1] = byte(s >> 16)
    x[0] = byte(s >> 24)
}

If so, why wasn't it written this way?

  • 写回答

1条回答 默认 最新

  • dt250827 2019-07-18 15:34
    关注

    The _ = assignment itself does nothing, but the index expression assigned to it is there to access the last element needed in the slice before a number of other lower index operations. This is an optimization to hint to the compiler that all the lower index operations on that value are safe, and the bounds checks can be elided. This is often call "Bounds Check Elimination"

    The primary reason the latter example isn't used is a second optimization, the bytes need to be read in-order so that the compiler can coalesce them into multi-byte loads.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大