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
+4.3k JavaScript : Rounding number to decimal formats to display currency
+29.9k Golang : Generate random string
+16.5k Golang : Capture stdout of a child process and act according to the result
+17k Golang : Get future or past hours, minutes or seconds
+16.1k Golang : Send email and SMTP configuration example
+4.7k Golang : micron to centimeter example
+16.3k Golang : read gzipped http response
+8.6k Golang : Get curl -I or head data from URL example
+32.7k Delete a directory in Go
+7.6k Golang : Gomobile init produce "iphoneos" cannot be located error
+5.2k Unix/Linux : How to find out the hard disk size?
+9.1k Golang : Qt Yes No and Quit message box example