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

huangapple go评论90阅读模式
英文:

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 &lt; b      // compiler error
d := a &lt; 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 {...}

所以,可以说,这个问题肯定是修复了

代码片段的Playground链接

英文:

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(&quot;Equal&quot;)
}

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.

huangapple
  • 本文由 发表于 2016年11月27日 00:08:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/40820275.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定