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).
Below is the syntax for type conversion in Go.
T(v)
Here, the value v
is converted to the type T
.
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)}
main
functionint
variable.int
to string
with the built-in strconv.Itoa
function.string
variable.T(v)
syntax to convert the int
variable to float
.float
variable.strconv.Itoa
.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)}