Learn How to do typecasting in Golang
In this article, you are going to learn about how to do typecasting in the Go language.
Typecasting refers to the term of assigning the value of one data type to another. It is also known as type conversion. You can generally do type conversion in two ways – implicit type conversion and explicit type conversion. Like other programming languages, the Go language does not support implicit type conversion. The reason behind it is the strong type system of the Go language.
To do type conversion in the Go language you have to follow the explicit approach. It gives you the advantage of certain characteristics of data type hierarchies, Let’s see the below code of examples of type conversion by following an explicit approach in the Go language:
package main
import "fmt"
func main() {
var totalNumber int = 1487
var totalStudents int = 27
var avg float32
// explicit type conversion
avg = float32(totalNumber) / float32(totalStudent)
fmt.Printf("The Average Number is = %f\\n", avg)
}
// Output : The Average Number is = 55.074074
Here, we have declared the totalNumber and totalStudents type as integer and later on, we have declared it as float32 explicitly while calculating the average and you can see the output is a float number.
We have discussed that the Go language does not support the implicit method of type conversion in the earlier section of this article. Let’s see what happens if you try to convert a type implicitly in the Go language:
package main
import "fmt"
func main() {
var totalNumber int = 1487
var totalStudent int = 27
var avg float32
avg = totalNumber / totalStudent
fmt.Printf("The Average Number is = %f\\n", avg)
}
Output:
Here, you just simply get an error and that is you can not use type int as type float32. So you need to do the type conversion explicitly in the Go language.