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
+19.2k Golang : Delete item from slice based on index/key position
+18.4k Golang : Write file with io.WriteString
+11k Golang : Read until certain character to break for loop
+11k How to test Facebook App on localhost ?
+21.6k SSL : How to check if current certificate is sha1 or sha2
+8k Golang : Sort words with first uppercase letter
+18.7k Unmarshal/Load CSV record into struct in Go
+8.9k Golang : Populate or initialize struct with values example
+15.4k Golang : invalid character ',' looking for beginning of value
+12k Golang : Find and draw contours with OpenCV example
+6.3k Golang : How to search a list of records or data structures
+9.3k Golang : Play .WAV file from command line