Type casting is the process of converting the value of one data type (integer, float, string) to another data type. For example,
Here, int(floatValue) specifies that we are converting the float value 9.8 to 9.
Since we are manually performing the type conversion, this is called explicit type casting in Go.
Golang provides various predefined functions like int(), float32(), string(), etc to perform explicit type casting.
Let's see some of the examples of explicit type casting:
Output
Here, we have used the function int() to convert the value from 5.45 to 5.
In this case, we are manually converting the type of one type to another. Hence, it is called explicit type casting.
Output
Here, we have used the function float32() to convert an integer value to float. The integer value 2 changed to 2.000000 after the type casting.
In implicit type casting, one data type is automatically converted to another data type. However, Go doesn't support implicit type casting. For example,
In the above example, we have created an int type variable named number. Here, we are trying to assign a floating point value 4.34 to the int variable.
When we run this program, we will get an error:
This is because Golang doesn't support implicit type conversion.
Output
In the above example, we have created an integer variable named number1 and a float variable named number2. Notice the line,
Here, we are adding values of two different types (float and int). Since Go doesn't support implicit type casting, we need to change the value of one type to another.
This is why we have used float32(number1) to convert the int type variable number to float type.