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
+12.1k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+9.4k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+27.9k Golang : Save map/struct to JSON or XML file
+9.6k Golang : Create matrix with Gonum Matrix package example
+8.9k Golang : Get current, epoch time and display by year, month and day
+11.2k Golang : Forwarding a local port to a remote server example
+5.8k Default cipher that OpenSSL used to encrypt a PEM file
+3.9k Linux : How to set root password in Linux Mint
+28.8k Get client IP Address in Go
+18.9k Golang : Count number of digits from given integer value
+6.3k Golang : Of hash table and hash map
+8.4k Golang : How to generate Code 39 barcode?