20

有人可以告诉我 go 是否支持数字类型的自动转换。现在我必须手动将所有计算的结果转换为 int 或 int64 并跟踪我正在使用的数字类型。

4

3 回答 3

14

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

从语言规范:

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

于 2012-12-13T01:30:19.467 回答
4

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.

type conversion error

于 2012-12-13T03:26:14.533 回答
0

您必须手动在类型之间进行转换,例如

var b byte = byte(x % 256);
于 2017-01-01T23:33:42.140 回答