Understand How Type Conversion Works In Golang

Understand How Type Conversion Works In Golang

Type conversion is a seemingly simple concept in Golang, but if you are new to programming or new to the language, then anything can feel tricky to understand fully at first, no matter how simple they appear to experts. The goal of this article is to provide a second-hand explanation of Golang’s type conversion with examples.

Prerequisites: The primary audience for this article is somebody who has learned about type conversion in Golang but needs yet another explanation to help them grasp the concept better. However, having knowledge of Golang's fundamentals, like variable declaration and functions, you would still be capable of making sense of the article.

What is Type Conversion In Golang

Type conversion is a way to convert a value of one data type to a different data type. Type conversion here is similar to what is known as Type casting in some other languages, like C. However in Go, the term typecasting does not exist, instead there is just type conversion. This is most likely because in Golang type conversion works a little differently. You need to always explicitly specify that you are converting a data of one type to a different type for type conversion to take place. In some other languages like C again, implicit type conversion is possible by simply using a value where you need it, and the compiler automatically converts the value to the appropriate data type suitable for the operation that is carried out. An example showing the syntax for type conversion in Go:

package main

import "fmt"

func main() {

    var price float64 = 2.5
    var amount int = 5
    total := price * float64(amount)    // convert amount to float64
    fmt.Println("Total price is this:", total)
}

// Output: Total price is this: 12.5

We see that in the above code, in order to perform arithmetic operation with both variables and get the total, we needed to first convert price which was originally an integer to a float64 with float(amount). Failure to do this would throw a compile-time error.

When you create a type alias and need to covert one value to the type alias, you use the same syntax:

type userId int  // Create type alias
newUser := userId(9)  // Convert 9 from int to userId

Why Type Conversion

The common reason for carrying out type conversion in Go is to take advantage of certain characteristics of a data type while making use of a value from a variable of a different data type. So since the value you intend to use does not possess the properties you require for an action, you convert them to a type that possesses those properties. Note that when you convert the value from a variable to a different data type, the original variable declaration remains of it’s assigned or asserted data type, it does not change type. An example using the code we wrote earlier, this time we also print out the type of amount after converting the value from it:


package main

import "fmt"

func main() {

    var price float64 = 2.5
    var amount int = 5
    total := price * float64(amount) // convert amount to float64
    fmt.Println("Total price is this:", total)
    fmt.Printf("type of amount is still %T", amount) // print out the data type of `amount`
}

// Output: 
// Total price is this: 12.5
// type of amount is still int

We used the %T verb inside a Printf to print out the data type of the variable amount, and we can see that it still remained an integer.

Some Other Ways to Perform Type Conversion In Go

In the previous examples, we have only converted between number types and used the T() syntax. We have converted from integers to floats which are both number types. Note that when you convert a float to an integer, the new number will loose any decimal places it had when in it was still a float. E.g when you covert 15.6 from float to int, you get 15 and no longer 15.6. Do keep this in mind when you convert from float to int.

Apart from converting between numbers, we can also convert between strings and numbers. To do this you will need to import and use the strconv package from the Go standard library. Lets consider some examples of how to use this package:

Convert from string to integer: For string to integer we use the strconv.Atoi() function. Consider how to do this from this example program to keep track of how many bus seats are remaining after a user buys their travelng ticket:

package main

import (
    "fmt"
    "log"
    "strconv"
)

func main() {
    var seatsRemaining int = 9

    var howManyTickets string = "3"

    /** Convert howManyTickets to integer and assign it to numOfTickets **/
    numOfTickets, err := strconv.Atoi(howManyTickets)

    // Check if an error occurred during the conversion
    if err != nil {
        log.Fatal(err)
    }

    seatsRemaining -= numOfTickets

    fmt.Println(seatsRemaining)

}

// Output: 6

There is always a chance that your conversion from string to integer might fail, so it’s common to check if an error occurred , if so handle it, otherwise move on with the program. After the above code has ran with without an error, we should get 6 printed out.

Convert from number to string: The function to use in this case is the strconv.Itoa() function. In this example let’s simply print out a message telling a user how many of the bus seats are remaining, but because the number of seats remaining is stored as a number, we need to convert the number to a string to include it in our message:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    …
    // Number of bus seats remaining
    seatsRemaining := 6
    fmt.Println("there are", strconv.Itoa(seatsRemaining), " seats remaining in this bus.")

}

Conclusion

So far we have explained further how type conversion works in Go alongside the syntax for it and what package to use when converting between strings and numbers. The key thing to take away is that you must explicitly convert between types in Go because there’s no support for implicit conversion, and when you do convert a value between types, the initial variable declaration where the value was stored remains of its original type, it does not change.