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
+6.3k Golang : Create zip/ePub file without compression(use Store algorithm)
+6k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+11.6k Python : Convert IPv6 address to decimal and back to IPv6
+9.8k Golang : Delay or limit HTTP requests example
+4.5k Golang : Shortening import identifier
+5.4k Golang : Find the longest line of text example
+5.1k Golang : Selection sort example
+5.6k Golang : Calculate pivot points for a cross
+12k Golang : Generate Code128 barcode
+4.1k Golang : Get FX sentiment from website example
+18.2k Golang : Check if os.Stdin input data is piped or from terminal
+5.5k Golang : How to setup a disk space used monitoring service with Telegram bot