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
+10.4k Golang : Interfacing with PayPal's IPN(Instant Payment Notification) example
+6.9k Golang : Gorrila mux.Vars() function example
+14k Golang : How to convert a number to words
+6.9k Golang : Transform lisp or spinal case to Pascal case example
+9.9k Golang : Edge detection with Sobel method
+10.3k Golang : Select region of interest with mouse click and crop from image
+17.3k Golang : Parse date string and convert to dd-mm-yyyy format
+11.5k Golang : Gorilla web tool kit secure cookie example
+8.6k Golang : Find network service name from given port and protocol
+7.3k Golang : Rot13 and Rot5 algorithms example
+6.6k Fix sudo yum hang problem with no output or error messages
+5.1k Javascript : Change page title to get viewer attention