Casting between number types in golang

2020-08-09 07:00发布

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.

3条回答
beautiful°
2楼-- · 2020-08-09 07:30

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.

查看更多
ゆ 、 Hurt°
3楼-- · 2020-08-09 07:30

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

var b byte = byte(x % 256);
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2020-08-09 07:44

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

查看更多
登录 后发表回答