How to find the type of an object in Go?

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

    If we have this variables:

    var counter int = 5
    var message string  = "Hello"
    var factor float32 = 4.2
    var enabled bool = false
    

    1: fmt.Printf %T format : to use this feature you should import "fmt"

    fmt.Printf("%T \n",factor )   // factor type: float32
    

    2: reflect.TypeOf function : to use this feature you should import "reflect"

    fmt.Println(reflect.TypeOf(enabled)) // enabled type:  bool
    

    3: reflect.ValueOf(X).Kind() : to use this feature you should import "reflect"

    fmt.Println(reflect.ValueOf(counter).Kind()) // counter type:  int
    

提交回复
热议问题