英文:
Does Go fix or share C's hazardous implicit -> unsigned conversion?
问题
在《21世纪的C语言》一书中,Ben Klemens描述了C语言如何自动将有符号数转换为无符号数,例如在比较表达式中。Go语言是否也有这种危险的行为,或者Go语言对此有不同的处理方式?
英文:
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?
答案1
得分: 2
在Go语言中,没有隐式转换。如果要比较或进行算术运算的两个值的类型不同,必须进行手动和显式的类型转换。
a := 3 // 数值常量3默认为int类型
b := uint(2)
c := a < b // 编译器错误
d := a < int(b) // 正确
英文:
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
答案2
得分: 2
Go在所有操作中,包括比较,只使用显式类型转换。
var a uint64
var b int64
a = 1
b = 1
if a == b {
fmt.Println("Equal")
}
这段代码会导致错误:
tmp/sandbox428200464/main.go:13: invalid operation: a == b (mismatched types uint64 and int64)
要进行比较,你必须显式地将变量转换为相同的类型:
if int64(a) == b {...}
所以,可以说,这个问题肯定是修复了。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论