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
+15k Golang : Find location by IP address and display with Google Map
+8.5k Golang : On lambda, anonymous, inline functions and function literals
+5.5k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+48.2k Golang : Upload file from web browser to server
+8.5k Golang : Get final balance from bit coin address example
+11.4k Golang : Gorilla web tool kit secure cookie example
+10.3k Golang : How to delete element(data) from map ?
+7.6k Golang : How to feed or take banana with Gorilla Web Toolkit Session package
+7.5k Golang : Example of how to detect which type of script a word belongs to
+8.5k Golang : Gorilla web tool kit schema example
+21.7k Golang : Convert seconds to minutes and remainder seconds
+15.2k Golang : rune literal not terminated error