简体   繁体   English

Go会修复或共享C的危险隐式->无符号转换吗?

[英]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. 本·克莱门斯(Ben Klemens)在《 21世纪C》中描述了C如何在比较表达式中自动将有符号数转换为无符号数。 Does Go share this same hazardous behavior, or does Go approach it differently? Go是否具有相同的危险行为,还是Go采取不同的处理方式?

There are no implicit conversions in Go. 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. Go仅对所有操作(包括比较)使用显式类型转换

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) tmp / sandbox428200464 / main.go:13:无效操作:a == b(uint64和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. 片段的Playgound

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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