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
+26.5k Get file path of temporary file in Go
+24.6k Mac/Linux and Golang : Fix bind: address already in use error
+20.5k Golang : Match strings by wildcard patterns with filepath.Match() function
+3.9k Javascript : How to get width and height of a div?
+25.1k Golang : Encrypt and decrypt data with AES crypto
+32k Golang : Converting a negative number to positive number
+4.7k Fix yum-complete-transaction error
+8.8k Golang : Get current, epoch time and display by year, month and day
+16.5k Golang : Simple client server example
+9.8k Golang : Web routing/multiplex example
+14.4k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content