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
+4.9k Golang : Get Hokkien(福建话)/Min-nan(閩南語) Pronounciations
+7.9k Golang : Find the length of big.Int variable example
+9.3k JavaScript/JQuery : Detect or intercept enter key pressed example
+9.5k Golang : Fix go.exe is not compatible with the version of Windows you're running
+4.7k List of Golang XML tutorials
+12.9k Golang : syscall.Socket example
+32.6k Golang : Proper way to set function argument default value
+10k Golang : How to pipe input data to executing child process?
+5.9k Golang : How to call function inside template with template.FuncMap
+21.7k Golang : Gorilla mux routing example
+7.6k Golang : Set or add headers for many or different handlers
+11.5k Golang : How to calculate the distance between two coordinates using Haversine formula