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
+20.8k Golang : Get password from console input without echo or masked
+19k Golang : Get RGBA values of each image pixel
+16.5k Golang : read gzipped http response
+5.9k Golang : Get Hokkien(福建话)/Min-nan(閩南語) Pronounciations
+4.6k Fix Google Analytics Redundant Hostnames problem
+4.3k Java : Generate multiplication table example
+11k Use systeminfo to find out installed Windows Hotfix(s) or updates
+7.8k Golang : Multiplexer with net/http and map
+22.3k Generate checksum for a file in Go
+19.7k Golang : How to get own program name during runtime ?
+5.8k Javascript : Get operating system and browser information
+14.2k Golang : Overwrite previous output with count down timer