Golang : How to check variable or object type during runtime?
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!
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
+24.4k Golang : Time slice or date sort and reverse sort example
+5.3k Golang : Pad file extension automagically
+12.2k Golang : List running EC2 instances and descriptions
+29.8k Golang : How to get HTTP request header information?
+5.5k PHP : Fix Call to undefined function curl_init() error
+5.2k Golang : Calculate half life decay example
+8.2k Golang : Configure Apache and NGINX to access your Go service example
+11.1k Golang : Fix - does not implement sort.Interface (missing Len method)
+6.9k Golang : constant 20013 overflows byte error message
+6.5k Golang : How to determine if request or crawl is from Google robots
+13.7k Golang : Check if an integer is negative or positive
+12k Golang : Save webcamera frames to video file