Golang : Detect variable or constant type
Problem :
You have a variable or constant and you want to know which type the variable belongs to.
Solution :
Use the reflect
package. From the overview itself :
A call to ValueOf returns a Value representing the run-time data. Zero takes a Type and returns a Value representing a zero value for that type.
For example :
package main
import (
"fmt"
"reflect"
"strconv"
)
func main() {
var str string = "123456789"
sixtyFour, err := strconv.ParseInt(str, 10, 64) // use base 10 for sanity
if err != nil {
fmt.Println(err)
}
fmt.Printf("The type of str is %v \n", reflect.TypeOf(str))
fmt.Printf("The type of sixtyFour is %v \n", reflect.TypeOf(sixtyFour))
}
Output :
The type of str is string
The type of sixtyFour is int64
Reference :
See also : Golang : Constant and variable names in native language
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.5k Golang: Prevent over writing file with md5 hash
+10.5k Golang : Convert IPv4 address to packed 32-bit binary format
+7k Golang : automatically figure out array length(size) with three dots
+15.5k Golang : When to use init() function?
+5.2k Golang : Accessing dataframe-go element by row, column and name example
+18.6k Golang : Get password from console input without echo or masked
+14.2k Golang : Convert slice to array
+9.6k Golang : How to calculate the distance between two coordinates using Haversine formula
+8.7k Use systeminfo to find out installed Windows Hotfix(s) or updates
+35.6k Golang : Remove dashes(or any character) from string
+12.4k Golang : Parsing or breaking down URL
+13.7k Golang : Set up source IP address before making HTTP request