GoLang - Type Casting

3 minute read

In this tutorial, you will learn about Type casting in Go Programming with the help of example.

In Go programming, type casting, also known as type conversion, allows you to convert a value from one data type to another. It enables you to perform operations or assignments involving different types of data. In this tutorial, we will explore type casting in Go programming, along with examples, using simple and easy-to-understand language. So let’s get started and learn about type casting in Go!

Numeric Type Conversion

Go requires explicit type conversion for all type changes — there is no implicit type conversion in Go. Even closely related types like int and float64 must be converted explicitly using the target type as a function.

Example:

package main

import "fmt"

func main() {
    var x = 10
    var y = 3.14

    var result = float64(x) + y

    fmt.Println("Result:", result)
}

In the example above, we have an integer variable x and a float variable y. We use explicit type conversion to convert x from an integer to a float using float64(x). Without this conversion, the code would not compile because Go does not allow operations between mismatched types.

Explicit Type Conversion

In other cases, when the type conversion is not implicitly done by the compiler, you can perform explicit type casting using the desired type in parentheses before the value you want to convert.

Example:

package main

import "fmt"

func main() {
    var x = 3.14
    var y = int(x)

    fmt.Println("Value of x:", x)
    fmt.Println("Value of y:", y)
}

In this example, we have a float variable x. We explicitly convert x to an integer using int(x), and the result is assigned to the variable y. The values of x and y are then printed.

Type Assertion

Type assertion is used to extract the underlying value of an interface variable and perform operations on it by explicitly specifying its type.

Example:

package main

import "fmt"

func main() {
    var val interface{} = "Hello, World!"

    str, ok := val.(string)
    if ok {
        fmt.Println("String Value:", str)
    } else {
        fmt.Println("Not a string!")
    }
}

In this example, we have an interface variable val that holds the value “Hello, World!”. We use type assertion with val.(string) to extract the underlying string value and assign it to the variable str. We also use the second return value ok to check if the type assertion was successful. If the assertion succeeds, we print the string value; otherwise, we indicate that it is not a string.

Conclusion

Type casting in Go programming allows you to convert values from one data type to another, enabling you to perform operations involving different types. In this tutorial, we explored numeric type conversion, explicit type conversion, and type assertion in Go. Remember that Go requires all type conversions to be explicit — there is no implicit conversion. By understanding these concepts and utilizing type conversion appropriately, you can handle data of various types effectively in your Go programs. So go ahead, practice type conversion, and enhance your programming capabilities in Go!

Frequently Asked Questions

Q: Does Go support implicit type conversion?

No. Go has no implicit type conversion. Every type change must be done explicitly using the target type as a function, such as float64(x) or int(y). This design prevents subtle data loss bugs that can occur in languages with implicit conversions.

Q: What happens when I convert a float to an int?

The decimal portion is truncated (not rounded). For example, int(3.9) gives 3 and int(-2.7) gives -2. If you need rounding, use math.Round() before converting.

Q: Can I convert a string to an int directly?

No. You cannot use int("42") in Go — that would try to interpret the string as a Unicode code point. Instead, use the strconv package: strconv.Atoi("42") converts a string to an integer and returns an error if the string is not a valid number.

Q: What is the difference between type conversion and type assertion?

Type conversion changes a value from one concrete type to another (e.g., float64(x)). Type assertion extracts the underlying concrete value from an interface variable (e.g., val.(string)). They serve different purposes and are used in different contexts.

Updated: