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
+15.4k Golang : invalid character ',' looking for beginning of value
+13.8k Golang : Convert spaces to tabs and back to spaces example
+18k Golang : How to log each HTTP request to your web server?
+5.6k Python : Print unicode escape characters and string
+10.6k Golang : ISO8601 Duration Parser example
+24.5k Golang : Time slice or date sort and reverse sort example
+5.7k List of Golang XML tutorials
+7k Golang : Levenshtein distance example
+13.5k Golang : How to get year, month and day?
+8.1k Golang : Append and add item in slice
+19.1k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+8.6k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared