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.
Asked
Active
Viewed 3.4k times
3 Answers
15
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.
5
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.

gprasant
- 15,589
- 9
- 43
- 57
-
5`int` is most certainly not specified as `int32`. It varies by implementation and platform. – Dustin Dec 13 '12 at 04:48
-
-
4`int` and `int32` are not necessarily the same Type: http://golang.org/ref/spec#Numeric_types – mhutter Dec 17 '13 at 15:15
-
Illuminating answer. I quoted you here https://stackoverflow.com/a/62737936/12817546. – Jul 07 '20 at 07:49
1
You have to convert between types manually, e.g.
var b byte = byte(x % 256);

jameshfisher
- 34,029
- 31
- 121
- 167
-
Elucidate answer I quoted. Did I add to it? See https://stackoverflow.com/a/62737936/12817546 – Jul 07 '20 at 21:44