Walter Bright:

1. Go determines the type of (e1 op e2) as the type of the first operand.

  http://golang.org/ref/spec#Arithmetic_operators

I consider this not only surprising (as we expect + to be commutative) but can lead to unexpected truncation, as in (byte = byte + int32).

I don't know much about Go, but I have read some Go programs, and that comment looks suspicious. So I have created a little Go program:


package main
import ("fmt")
func main() {
    var x byte = 10;
    var y int = 1000;
    z := x + y
    fmt.Println(z)
}


If you don't have a Go compiler you can try some code here:
http://play.golang.org/

The result:
http://play.golang.org/p/iP20v0r566

It gives:
prog.go:6: invalid operation: x + y (mismatched types byte and int)

So despite what the docs say, it seems the two types need to be the same for the sum to work?

While this program compiles:


package main
import ("fmt")
func main() {
    var x byte = 10;
    var y int = 1000;
    z1 := int(x) + y
    fmt.Println(z1)
    z2 := x + byte(y)
    fmt.Println(z2)
}


And prints:
1010
242

Bye,
bearophile

Reply via email to