I am new to Go and I am learning my way through its features. I have a question about the use of integer constants in certain operations. I tried some code in Go Playground which had the following lines
var i int8 = 0
var j int8 = i - 128
The statement defining variable j gives the error “constant 128 overflows int8” because Go deals with 128 as the constant as not -128. On the other hand, the following statements work fine presumably because Go is looking at the constant -128 and not 128.
var i int8 = 0
var j int8 = -128 + i
var i int8 = 0
var j int8 = i + (-128)
When subtracting an integer constant (as in i - 128) doesn’t it make more sense to take the negative of the constant for limit checking? Conversely, I see that var j int8 = i - -128 does not register an error, which it would if one were to take the negative of the constant -128 for limit checking.
Your first example applies a rule for binary operators.
package main
func main() {
var i int8 = 0
// constant 128 overflows int8
var j int8 = i - 128
// constant 128 overflows int8
var k int8 = i - int8(128)
_, _, _ = i, j, k
}
Your second and third examples apply a rule for unary operators before applying a rule for binary operators. Unary operators have the highest precedence.
package main
func main() {
var i int8 = 0
var j int8 = -128 + i
var k = int8(-128) + i
_, _, _ = i, j, k
}
package main
func main() {
var i int8 = 0
var j int8 = i + (-128)
var k int8 = i + int8(-128)
_, _, _ = i, j, k
}