How to find the type of an object in Go?

前端 未结 14 1091
余生分开走
余生分开走 2020-12-12 09:16

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 ?

相关标签:
14条回答
  • 2020-12-12 09:38

    You can just use the fmt package fmt.Printf() method, more information: https://golang.org/pkg/fmt/

    example: https://play.golang.org/p/aJG5MOxjBJD

    0 讨论(0)
  • 2020-12-12 09:42

    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

    0 讨论(0)
提交回复
热议问题