Casting between number types in golang

2020-08-09 06:50发布

问题:

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:

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:

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:

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

var b byte = byte(x % 256);