In Go, type casting allows us to ensure the data compatibility or to perform specific operations that require different data types to work together.
In this tutorial, will walk you through the basics of type casting in Go and cover the examples of various type conversion operations in the language.
What Is Type Casting?
Type casting, also known as type conversion, refers to the process of converting a value from one data type to another.
In Go, we can perform the type casting using either the type assertions or type conversion operators.
Since Go is a statically typed language, the compiler requires us to define the explicit data type of a given value.
Luckily, with the use of casting, we can change the type of a variable, when necessary, without violating Go’s strong type system.
Golang Type Casting
Type Conversion Operators
One of the common ways of converting the data types in Go is using the type conversion operators.
These operators allow us to explicitly change the type of a value as demonstrated in the following syntax example:
Here, the “targetType” is the target data type and “variable” is the value that we wish to convert.
We have access to several built-in type conversion functions in Go as follows:
Integer to Float
To convert a given integer value into a float, we can use the “float64” function as demonstrated in the following example:
floatVar := float64(intVar)
This should convert the input integer into a floating point value.
Float to Integer
We can also convert a given floating point value into an integer using the int() function as shown in the following example:
intVar := int(floatVar)
The “int” function automatically truncates the floating part of the value, leaving only the integer.
String to Byte Slice
We can also use the type casting to convert a string into a byte slice and vice versa. This is especially useful when dealing with encoding and decoding operations.
An example is as follows:
import "fmt"
func main() {
str := "https://linuxhint.com"
byteSlice := []byte(str)
str2 := string(byteSlice)
fmt.Println("byte slice:", byteSlice)
fmt.Println("string:", str2)
}
This allows us to convert a string into a byte slice and a byte slice into a string.
Numeric to String
We can also convert a given numeric value into a string using the “Sprintf” function from the “fmt” package as follows:
import "fmt"
func main() {
num := 314
str := fmt.Sprintf("%d", num)
fmt.Printf("num: %d, string: %s\n", num, str)
}
String to Numeric
The reverse is also true. To convert a string into a numeric representation, we can use the Atoi() function from the “strconv” package.
An example is as follows:
import (
"fmt"
"strconv"
)
func main() {
str := "314"
num, err := strconv.Atoi(str)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("string: %s, num: %d\n", str, num)
}
The function returns both the numeric value and an error in case of conversion failure.
Type Assertion Operators
Type assertion is a feature that allows us to extract the underlying value from an interface type when we know for sure that it is a concrete type.
Type assertions are very useful when working with interfaces.
The basic syntax is as follows:
Here, the parameters are described as follows:
- value – The extracted value.
- ok – A Boolean that indicates whether the assertion is successful.
- interfaceValue -The value of an interface type.
- TargetType – The desired type.
Consider an example as shown in the following:
import "fmt"
func main() {
var val interface{} = 314
num, ok := val.(int)
if ok {
fmt.Printf("value: %d, type: %T\n", num, num)
} else {
fmt.Println("assertion failed")
}
}
In this example, we create a “val” interface that contains an integer. We then use a type assertion to extract the integer value along with a Boolean that indicates whether the assertion is successful.
Conclusion
In this tutorial, we learned everything there is to know about type conversion when it comes to the Go programming language.