简体   繁体   中英

Does Go fix or share C's hazardous implicit -> unsigned conversion?

In "21st Century C", Ben Klemens describes how C automatically converts signed numbers to unsigned, in comparison expressions for example. Does Go share this same hazardous behavior, or does Go approach it differently?

There are no implicit conversions in Go. In order to compare or do arithmetic with two values of different types, you must do manual and explicit type conversion.

a := 3          // numerical constant 3 defaults to int
b := uint(2)
c := a < b      // compiler error
d := a < int(b) // OK

Go uses only explicit type conversions for all the operations including comparison.

var a uint64
var b int64

a = 1
b = 1
if a == b {
    fmt.Println("Equal")
}

This snippet is going to cause an error:

tmp/sandbox428200464/main.go:13: invalid operation: a == b (mismatched types uint64 and int64)

To do the comparison you must cast the variables to the same type explicitly:

if int64(a) == b {...}

So, definitely yes , it is fixed if one can say so.

Playgound for the snippet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM