英文:
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,尽管它们的大小相同。
英文:
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.
答案3
得分: 1
你必须手动在不同类型之间进行转换,例如:
var b byte = byte(x % 256);
英文:
You have to convert between types manually, e.g.
var b byte = byte(x % 256);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论