How do I find the type of an object in Go? In Python, I just use typeof
to fetch the type of object. Similarly in Go, is there a way to implement the same ?
You can use: interface{}..(type)
as in this playground
package main
import "fmt"
func main(){
types := []interface{} {"a",6,6.0,true}
for _,v := range types{
fmt.Printf("%T\n",v)
switch v.(type) {
case int:
fmt.Printf("Twice %v is %v\n", v, v.(int) * 2)
case string:
fmt.Printf("%q is %v bytes long\n", v, len(v.(string)))
default:
fmt.Printf("I don't know about type %T!\n", v)
}
}
}
you can use reflect.TypeOf
.
int
, string
): it will return its name (e.g.: int
, string
) <package name>.<struct name>
(e.g.: main.test
)To get a string representation:
From http://golang.org/pkg/fmt/
%T a Go-syntax representation of the type of the value
package main
import "fmt"
func main(){
types := []interface{} {"a",6,6.0,true}
for _,v := range types{
fmt.Printf("%T\n",v)
}
}
Outputs:
string
int
float64
bool
I found 3 ways to return a variable's type at runtime:
Using string formatting
func typeof(v interface{}) string {
return fmt.Sprintf("%T", v)
}
Using reflect package
func typeof(v interface{}) string {
return reflect.TypeOf(v).String()
}
Using type assertions
func typeof(v interface{}) string {
switch v.(type) {
case int:
return "int"
case float64:
return "float64"
//... etc
default:
return "unknown"
}
}
Every method has a different best use case:
string formatting - short and low footprint (not necessary to import reflect package)
reflect package - when need more details about the type we have access to the full reflection capabilities
type assertions - allows grouping types, for example recognize all int32, int64, uint32, uint64 types as "int"
reflect package comes to rescue:
reflect.TypeOf(obj).String()
Check this demo
Best way is using reflection concept in Google.
reflect.TypeOf
gives type along with the package name
reflect.TypeOf().Kind()
gives underlining type