Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
go
communitycreator

How to perform type conversion in Go

Vafa Batool

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 main
import ("fmt"
        "strconv" //this library is used for type conversions for strings
) 


func main() {

  // declaring a variable with int data type  
  var num1 int = 5 
  fmt.Println(num1)
  
  // converting int to string using the built-in strconv.Itoa function
  var str1 string = strconv.Itoa(num1)
  
  fmt.Println(str1)

  //converting int to float64 
  var num2 float64 = float64(num1)

  fmt.Println(num2)

  // we can also use short variable declaration for type conversion

  num3:= 10 

  str2:= strconv.Itoa(num3)

  fmt.Println(num3, str2)
  
  
}

Explanation

  • In lines 1 to 4, we import the relevant libraries.
  • In line 7, we define our main function
  • In lines 10 and 11, we declare and print an int variable.
  • In line 14, we convert an int to string with the built-in strconv.Itoa function.
  • In line 16, we print the converted string variable.
  • In line 19, we use the T(v) syntax to convert the int variable to float.
  • In line 21, we print the converted float variable.
  • 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 main
import "fmt"
/* For exercises uncomment the imports below */
// import "strconv"
// import "encoding/json"
func main() {
    var num1 int = 15

    fmt.Println(num1)

    //trying to store an int into float64 variable without explicitly stating the type
    var 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 main
import "fmt"
/* For exercises uncomment the imports below */
// import "strconv"
// import "encoding/json"
func main() {
    var num1 int = 15

    fmt.Println(num1)

    //explicitly stating the type now
    var num2 float64 = float64(num1)

    fmt.Println(num2)

}

RELATED TAGS

golang
go
communitycreator
RELATED COURSES

View all Courses

Keep Exploring