Type Conversion in Go

Type Conversion in Go

In this tutorial, we are going to discuss type conversion in Golang. Type conversion is a way to convert a variable from one data type to another data type.

Type Conversion in Go

For example, you can typecast long to int if you want to store a long value into a simple integer. You can convert values from one type to another using the cast operator.

The syntax for general type casting is pretty simple. Just use that other type name as a function to convert that value.

v := typeName(otherTypeValue)

Go is very strict about explicit typing. There is no automatic type of promotion or conversion. Let’s look at what this means with an example.

package main

import (
     "fmt"
)

func main() {
     i := 10       //int
     j := 15.5     //float64
     sum := i + j  //int + float64 not allowed
     fmt.Println(sum)
}

The above code is perfectly legal in some other programming languages. But in the case of Golang, this won’t work. i is of type int, and j is of type float64. We are trying to add 2 numbers of different types, which is not allowed.

When you run the program, you will get main.go:10: invalid operation: i + j (mismatched types int and float64)

Run in playground

To fix the error, both i and j should be of the same type. Let’s convert j to int. T(v) is the syntax to convert a value v to type T.

package main

import (
     "fmt"
)

func main() {
     i := 10           //int
     j := 15.5         //float64
     sum := i + int(j) //j is converted to int
     fmt.Println(sum)
}

Output

25

Run in playground

Now when you run the above program, you can see 25 as the output.

The same is the case with the assignment. Explicit type conversion is required to assign a variable of one type to another. This is explained in the following program.

package main

import (  
     "fmt"
)

func main() {  
     i := 100
     var j float64 = float64(i) //this statement will not work without explicit conversion
     fmt.Println("j value is : ", j)
}

Output

j value is :  100

In the above program, i is converted to float64 and then assigned to j. When you try to assign i to j without any type of conversion, the compiler will throw an error.

This is an essential concept in general programming. It converts one type to another, and whenever we need some other types for the expression type, casting helps.

That’s all about the Type Conversion in Go language. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Go language.!!

Type Conversion in Go
Scroll to top