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
+8.5k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+49.2k Golang : Check if item is in slice/array
+5.7k Golang : Check to see if *File is a file or directory
+23.8k Golang : missing Mercurial command
+20.8k Golang : Convert IP address string to long ( unsigned 32-bit integer )
+12.9k Golang : Generate QR codes for Google Authenticator App and fix "Cannot interpret QR code" error
+10k Golang : convert(cast) float to string
+20.9k Golang : Print out struct values in string format
+4.4k Golang : Dealing with backquote
+48.3k Golang : How to get time in milliseconds?
+5.5k Golang : Scanf function weird error in Windows
+38.9k Golang : How to check if a string contains another sub-string?