Odd behavior of Golang type conversion

27 Views Asked by At

For Golang code:


import "fmt"

func main() {
    var a uint8 = 1
    var b uint8 = 1
    fmt.Printf("%T %v %b\n", uint32(a^b)-1, uint32(a^b)-1, uint32(a^b)-1)
    fmt.Printf("%T %v %b\n", uint32(uint8(0))-1, uint32(uint8(0))-1, uint32(uint8(0))-1)
}

When I run the above code, what I expect to see is, for both

fmt.Printf("%T %v %b\n", uint32(a^b)-1, uint32(a^b)-1, uint32(a^b)-1)

and

fmt.Printf("%T %v %b\n", uint32(uint8(0))-1, uint32(uint8(0))-1, uint32(uint8(0))-1),

there should be constant -1 overflows uint32 error.

The actual execution result:

fmt.Printf("%T %v %b\n", uint32(a^b)-1, uint32(a^b)-1, uint32(a^b)-1) executed successfully.

fmt.Printf("%T %v %b\n", uint32(uint8(0))-1, uint32(uint8(0))-1, uint32(uint8(0))-1) caused constant -1 overflows uint32 error.

Could someone help explain this? Thanks!

0

There are 0 best solutions below