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?
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.