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
+11.8k Golang : Surveillance with web camera and OpenCV
+8.9k Golang : How to join strings?
+10.2k Golang : Channels and buffered channels examples
+5.2k Golang : Display packages names during compilation
+13.1k Swift : Convert (cast) Int to String ?
+11.8k Golang : Fuzzy string search or approximate string matching example
+15.4k Golang : Get HTTP protocol version example
+32.4k Golang : Convert []string to []byte examples
+10.8k Fix ERROR 1045 (28000): Access denied for user 'root'@'ip-address' (using password: YES)
+20.9k Golang : Saving private and public key to files
+3.9k Java : Random alphabets, alpha-numeric or numbers only string generator