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.

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

报告相同问题?

悬赏问题

  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义