在golang中的数字类型之间进行转换

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

Casting between number types in golang

问题

请问有人可以告诉我Go语言是否支持数字类型的自动转换吗?现在我必须手动将所有计算结果转换为int或int64,并且要跟踪我正在使用的数字类型。

英文:

Could someone please tell me if go supports automatic casting of numeric types. Right now I have to manually convert the results of all my computation to int or int64 and keep track of what numeric type I am using.

答案1

得分: 15

Go不会自动为您转换数字类型。

根据语言规范:

当在表达式或赋值中混合使用不同的数字类型时,需要进行转换。例如,int32和int虽然在特定架构上可能具有相同的大小,但它们不是相同的类型。

英文:

Go won't convert numeric types automatically for you.

From the language specification:

> Conversions are required when different numeric types are mixed in
an expression or assignment. For instance, int32 and int are not
the same type even though they may have the same size on a particular
architecture.

答案2

得分: 5

Go在数字类型中不支持隐式类型转换。

参考规范。我认为这是出于安全性和可预测性的原因。我发现的另一件有点奇怪/有趣的事情是,你甚至不能隐式地将int转换为int32,尽管它们的大小相同。

在golang中的数字类型之间进行转换
在golang中的数字类型之间进行转换

英文:

Go does not support implicit type conversions in numeric type.

Refer spec. I think this is for reasons of safety and predictability. One more thing I found was a bit weird/interesting is that you cant even convert from int to int32 implicitly, which is weird cause both are of the same size.

在golang中的数字类型之间进行转换
在golang中的数字类型之间进行转换

答案3

得分: 1

你必须手动在不同类型之间进行转换,例如:

var b byte = byte(x % 256);
英文:

You have to convert between types manually, e.g.

var b byte = byte(x % 256);

huangapple
  • 本文由 发表于 2012年12月13日 08:55:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/13851292.html
匿名

发表评论

匿名网友

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

确定