Golang : How to check variable or object type during runtime?
Tags : golang object-variable-type kind type-of reflect
Problem :
You need to determine the type of data your program is getting from the user input or the variable type during runtime. How to do that?
Solution :
Use the reflect
package's TypeOf(x).Kind()
function. For example :
package main
import (
"fmt"
"reflect"
)
func main() {
x := 1
typeX := reflect.TypeOf(x).Kind()
fmt.Println("X is type of : ", typeX)
y := float64(108.08)
typeY := reflect.TypeOf(y).Kind()
fmt.Println("Y is type of : ", typeY)
s := "hey!"
typeS := reflect.TypeOf(s).Kind()
if typeS == reflect.String {
fmt.Println("Variable S is type string!")
}
}
Output :
X is type of : int
Y is type of : float64
Variable S is type string!
Tags : golang object-variable-type kind type-of reflect
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+1.4k Golang : Getting Echo framework StartAutoTLS to work
+4.7k Golang : Setting variable value with ldflags
+1.9k Golang : How to get capacity of a slice or array?
+4.6k Golang : Bcrypting password
+5.2k Golang : delete and modify XML file content
+45.3k Golang : Convert HTTP Response body to string
+3k Golang : Error reading timestamp with GORM or SQL driver
+6.2k Golang : How to check if input from os.Args is integer?
+3.1k Golang : Resumable upload to Google Drive(RESTful) example
+1.8k Golang : Find relative luminance or color brightness
+1.3k Golang : Calculate half life decay example
592 Golang : Find the length of big.Int variable example