Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GOPL: Binary assignment operator "saves us from re-evaluation?"

Tags:

go

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?

like image 704
Dmitri Avatar asked Sep 14 '26 22:09

Dmitri


1 Answers

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.

like image 76
Dmitri Avatar answered Sep 17 '26 15:09

Dmitri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!