In this article, we will discuss Go casting with practical examples.
What is type casting in Golang
Converting a type into another type is an operation called casting, which works slightly differently for interfaces and concrete types:
- Interfaces can be casted to a concrete type that implements it. This conversion can return a second value (a Boolean) and show whether the conversion was successful or not. If the Boolean variable is omitted, the application will panic on a failed casting.
- With concrete types, casting can happen between types that have the same memory structure, or it can happen between numerical types:
type N [2]int // User defined type
var n = N{1,2}
var m [2]int = [2]int(N) // since N is a [2]int this casting is possible
var a = 3.14 // this is a float64
var b int = int(a) // numerical types can be casted, in this case a will be rounded to 3
var i interface{} = "hello" // a new empty interface that contains a string
x, ok := i.(int) // ok will be false
y := i.(int) // this will panic
z, ok := i.(string) // ok will be true
There's a special type of conditional operator for casting called type switch which allows an application to attempt multiple casts at once. The following is an example of using interface{}
 to check out the underlying value:
func main() {
var a interface{} = 10
switch a.(type) {
case int:
fmt.Println("a is an int")
case string:
fmt.Println("a is a string")
}
}
How to check type of a variable in golang
Before we start with type casting, we should know how to check type of any variable defined in the go code. We can use reflection provided by reflect
package for this purpose. The reflect package allows you to find out the data type of a variable. You can use the TypeOf()
function to find out the data type of a variable:
package main
import (
"fmt"
"os"
"reflect"
"time"
)
func main() {
var num1 = 10
fmt.Println(reflect.TypeOf(num1)) // "int"
var num2 = 10.00
fmt.Println(reflect.TypeOf(num2)) // "float64"
var name = "amit"
fmt.Println(reflect.TypeOf(name)) // "string"
var w = os.Stdout
fmt.Println(reflect.TypeOf(w)) // "*os.File"
start := time.Now()
fmt.Println(reflect.TypeOf(start)) // "time.Time"
}
Output:
int
float64
string
*os.File
time.Time
Get the code at Go playground
Some Go Cast Practical Examples
Example-1: Golang cast int64 to float64
Here we are adding all values of type int64 and converting them to floating point 64.
//main.go
package main
import "fmt"
func sum(a, b int64) float64 {
//convert the int64 into float64
return float64(a + b)
}
func main() {
var val int64 = 30
var val2 int64 = 4
fmt.Printf("Sum of values is %.2f", sum(val, val2))
}
Output:-
$ go run main.go
Sum of values is 34.00
Get the code at Go playground
Example-2: Golang cast float64 to int64
//main.go
package main
import "fmt"
func productOfFloatToInt(a, b float64) int64 {
// convert the float64 into int64
return int64(a * b)
}
func main() {
var val float64 = 20.0
var val2 float64 = 3.0
fmt.Printf("Product of values is %v", productOfFloatToInt(val, val2))
}
Output:-
$ go run main.go
Product of values is 60
Get the code at goplayground
Example-3: Golang cast string to integer using strconv.Atoi() function
Go standard library strconv package
provides us with strconv.Atoi()
function to convert string into integ
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
// enter any integer
dataInput := os.Args[1]
// convert string from os.Arg[] to int
value, err_ := strconv.Atoi(dataInput)
if err != nil{
fmt.Printf("This %v was encourtere converntng string to integer",err)
}
fmt.Printf("Value entered is %s of type %T to be converted to data type of %T the value is %02d. ", dataInput, dataInput, value, value)
}
Output:-
$ go run main.go 30
Value entered is 30 of type string to be converted to data type of int the value is 30.
Explanation:- We are using strconv package
to convert the value entered into the terminal, We use the os.Args[]
function from the os package to read users' argument which are of string data type.
Example-4 Golang cast integer to string using strconv.Itoa() function
Go standard library strconv package
provides us with strconv.Itoa()
 function to convert integer into string.
package main
import (
"fmt"
"strconv"
)
func main() {
fmt.Println("Enter any number")
var inputValue int
_, err := fmt.Scanf("%d", &inputValue)
if err != nil {
fmt.Println(err)
}
// convert int to string
value := strconv.Itoa(inputValue)
fmt.Printf("Value entered is %02d of %T data type to be converted to %T data type the value is %s. ", inputValue, inputValue, value, value)
}
Output:-
$ go run main.go
Enter any number
6
Value entered is 06 of int data type to be converted to string data type the value is 6.
Explanation:- we are using the strconv package
to convert the value entered into the terminal, We use the fmt.Scanf()
function to read users inputs and bind them to the define variable
Example-5: Golang cast string to float
In Go, we can convert string values into any integer or floating points data type. here we shall use strconv.ParseFloat()
function which accepts inputs of string as the first argument and floating point of either 64 or 32 as the second argument.
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
// enter any integer
inputValue := os.Args[1]
// convert string from os.Arg[] to int
value, err := strconv.ParseFloat(inputValue, 64)
if err != nil {
fmt.Printf("This %v was encountered convernting string to float64", err)
}
fmt.Printf("Value entered is %s of %T data type to be converted to %T data type the value is %.2f. ", inputValue, inputValue, value, value)
}
Output:-
$ go run main.go 300
Value entered is 300 of string data type to be converted to float64 data type the value is 300.00.
Example-6: Golang cast strings to bytes
In Go, A byte is an unsigned-bit integer that has a limit from 0-255 in the numerical range. Strings are slices of bytes. we use bufio package
to provide us with bufio.NewScanner(os.Stdin)
function to read users' inputs line by line and whole line content.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
// enter any string
fmt.Println("Enter any string ")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
text := scanner.Text()
// convert string to []bytes
value := []byte(text)
fmt.Printf("Value entered are [ %s ] of %T data type to be converted to %T data type the value is %v. ", text, text, value, value)
}
Output:-
$ go run main.go
Enter any string
Go Linux Cloud Study
Value entered are [ Go Linux Cloud Study ] of string data type to be converted to []uint8 data type the value is [71 111 32 108 105 110 117 120 32 67 108 111 117 100 32 83 116 117 100 121].
Summary
All languages support type casting and Golang is not an exceptional language. It's important to convert a value from one type to another based on need. However not all data types are supported but string, integer, and floating point are supported.
References
Related Keywords: golang cast to string, golang cast string to int, cast to int golang, golang check type of variable