Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting between number types in golang

Tags:

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.

like image 974
cobie Avatar asked Dec 13 '12 00:12

cobie


People also ask

How do you typecast in Golang?

As per Golang Specification, there is no typecasting word or terminology in Golang. If you will try to search Type Casting in Golang Specifications or Documentation, you will find nothing like this. There is only Type Conversion. In Other programming languages, typecasting is also termed as the type conversion.

Does Go support type conversion?

Golang Implicit Type CastingGolang does not support implicit type conversion because of its robust type system. Some languages allow or even require compilers to provide coercion.

What is integer type casting?

Type casting refers to changing an variable of one data type into another. The compiler will automatically change one type of data into another if it makes sense. For instance, if you assign an integer value to a floating-point variable, the compiler will convert the int to a float.


2 Answers

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.

like image 107
dskinner Avatar answered Sep 20 '22 21:09

dskinner


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 conversionerror

like image 32
gprasant Avatar answered Sep 21 '22 21:09

gprasant