dongqiu3709 2017-10-25 18:12
浏览 58
已采纳

GOPL:二进制赋值运算符“可以避免重新评估?”

Page 36 of the Go Programming Language (GOPL) contains the following:

Each of the arithmetic and bitwise binary operators has a corresponding assignment operator allowing, for example, the last statement to be rewritten as

count[x] *= scale

which saves us from having to repeat (and re-evaluate) the expression for the variable.

I do not understand the part about re-evaluation. Do the authors mean to say that

count[x] = count[x] * scale

and

count[x] *= scale

compile to different bytecode?

  • 写回答

1条回答 默认 最新

  • dongmi4927 2017-10-26 03:03
    关注

    The two versions may be functionally different (thank you for the hint, Volker):

    package main
    
    import "fmt"
    
    var idx int
    func n() int {
        idx++
        return idx - 1
    }
    
    func main() {
        var nums = [2](int){ 1, 2 }
        var adj = 10
    
        if true {
            nums[ n() ] += adj                   // Prints [11 2]
        } else {
            nums[ n() ] = nums[ n() ] + adj      // Prints [12 2]
        }
    
        fmt.Println("%v", nums)
    }
    

    (You can play with it here.)

    An equivalent C program behaves in exactly the same way.

    The fact that this was surprising to me is itself surprising: I seldom call functions to get an array index directly, so the thought never crossed my mind.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部