How to perform type conversion in Go
Type conversion of variables refers to storing the value of one data type in another. This normally occurs when the value of one variable is stored in another variable with a different data type. However, we cannot do this directly (implicit type conversion).
Syntax
Below is the syntax for type conversion in Go.
T(v)
Here, the value v is converted to the type T.
Code
Let’s look at a few examples of type conversion.
package mainimport ("fmt""strconv" //this library is used for type conversions for strings)func main() {// declaring a variable with int data typevar num1 int = 5fmt.Println(num1)// converting int to string using the built-in strconv.Itoa functionvar str1 string = strconv.Itoa(num1)fmt.Println(str1)//converting int to float64var num2 float64 = float64(num1)fmt.Println(num2)// we can also use short variable declaration for type conversionnum3:= 10str2:= strconv.Itoa(num3)fmt.Println(num3, str2)}
Explanation
- In lines 1 to 4, we import the relevant libraries.
- In line 7, we define our
mainfunction - In lines 10 and 11, we declare and print an
intvariable. - In line 14, we convert an
inttostringwith the built-instrconv.Itoafunction. - In line 16, we print the converted
stringvariable. - In line 19, we use the
T(v)syntax to convert theintvariable tofloat. - In line 21, we print the converted
floatvariable. - In lines 25 to 29, we use short variable declaration to perform the same principle of string conversion with
strconv.Itoa.
Error on implicit type conversion
As mentioned before, Go does not implicitly change the data type of a variable and gives an error if we try to do so.
Try running the following piece of code:
package mainimport "fmt"/* For exercises uncomment the imports below */// import "strconv"// import "encoding/json"func main() {var num1 int = 15fmt.Println(num1)//trying to store an int into float64 variable without explicitly stating the typevar num2 float64 = num1}
Here, we try to implicitly convert num1 to float and are dealt with an error. Hence, we are required to specify the data type during conversion.
Let’s look at the same example with the correction:
package mainimport "fmt"/* For exercises uncomment the imports below */// import "strconv"// import "encoding/json"func main() {var num1 int = 15fmt.Println(num1)//explicitly stating the type nowvar num2 float64 = float64(num1)fmt.Println(num2)}