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 just use the fmt package fmt.Printf() method, more information: https://golang.org/pkg/fmt/
example: https://play.golang.org/p/aJG5MOxjBJD
To get the type of fields in struct
package main
import (
"fmt"
"reflect"
)
type testObject struct {
Name string
Age int
Height float64
}
func main() {
tstObj := testObject{Name: "yog prakash", Age: 24, Height: 5.6}
val := reflect.ValueOf(&tstObj).Elem()
typeOfTstObj := val.Type()
for i := 0; i < val.NumField(); i++ {
fieldType := val.Field(i)
fmt.Printf("object field %d key=%s value=%v type=%s \n",
i, typeOfTstObj.Field(i).Name, fieldType.Interface(),
fieldType.Type())
}
}
Output
object field 0 key=Name value=yog prakash type=string
object field 1 key=Age value=24 type=int
object field 2 key=Height value=5.6 type=float64
See in IDE https://play.golang.org/p/bwIpYnBQiE