How to find the type of an object in Go?

前端 未结 14 1089
余生分开走
余生分开走 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:18

    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)
          }
        }
    }
    
    0 讨论(0)
  • 2020-12-12 09:22

    you can use reflect.TypeOf.

    • basic type(e.g.: int, string): it will return its name (e.g.: int, string)
    • struct: it will return something in the format <package name>.<struct name> (e.g.: main.test)
    0 讨论(0)
  • 2020-12-12 09:23

    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
    
    0 讨论(0)
  • 2020-12-12 09:25

    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"

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

    reflect package comes to rescue:

    reflect.TypeOf(obj).String()
    

    Check this demo

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

    Best way is using reflection concept in Google.
    reflect.TypeOf gives type along with the package name
    reflect.TypeOf().Kind() gives underlining type

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