Go Type Casting
Type casting, also known as type conversion, is the process of converting a value from one data type to another. In Go, you can use the following syntax to cast a value to a different data type:
newType := dataType(expression)Source:www.theitroad.com
Here, dataType
is the data type to which you want to convert the expression, and expression
is the value you want to convert.
Go supports both implicit and explicit type conversions. Implicit type conversion occurs automatically when the Go compiler converts values of one type to another type to satisfy a particular operation or expression. Explicit type conversion, on the other hand, requires the programmer to explicitly cast the value to the desired type using the above syntax.
Here's an example of type casting in Go:
var x int = 10 var y float64 = float64(x) fmt.Printf("x is of type %T and value %d\n", x, x) fmt.Printf("y is of type %T and value %f\n", y, y)
In this example, we first declare a variable x
of type int
with a value of 10
. We then declare another variable y
of type float64
and use the float64()
function to explicitly cast the value of x
to a float64
. Finally, we print out the types and values of x
and y
.
Output:
x is of type int and value 10 y is of type float64 and value 10.000000
As we can see, x
is of type int
and y
is of type float64
after the explicit type conversion.