0

In below code, in order to show the expected type, I have to create a new object and call reflect.TypeOf on it.

package main

import (
    "fmt"
    "reflect"
)

type X struct {
    name string
}

func check(something interface{}) {
    if _, ok := something.(*X); !ok {
        fmt.Printf("Expecting type %v, got %v\n", 
            reflect.TypeOf(X{}), reflect.TypeOf(something))
    }
}

func main() 
    check(struct{}{})
}

Perhaps that object creation is not an overhead, but I still curious to know a better way. Are there something like X.getName() or X.getSimpleName() in java?

icza
  • 389,944
  • 63
  • 907
  • 827
Tai Le
  • 102
  • 2
  • 10
  • 3
    Use `reflect.TypeOf((*X)(nil)).Elem()` to avoid having to create a value of `X`. For printing the type of a value, you may use `fmt.Printf("%T", something)`. – icza Oct 26 '18 at 09:28
  • Thank for `%T`. Could you please post it as an answer? – Tai Le Oct 26 '18 at 09:40

2 Answers2

3

To obtain the reflect.Type descriptor of a type, you may use

reflect.TypeOf((*X)(nil)).Elem()

to avoid having to create a value of type X. See these questions for more details:

How to get the string representation of a type?

Golang TypeOf without an instance and passing result to a func

And to print the type of some value, you may use fmt.Printf("%T, something).

And actually for what you want to do, you may put reflection aside completely, simply do:

fmt.Printf("Expecting type %T, got %T\n", (*X)(nil), something)

Output will be (try it on the Go Playground):

Expecting type *main.X, got struct {}
icza
  • 389,944
  • 63
  • 907
  • 827
0

Using reflects is almost always a bad choice. You can consider using one of the following ways

Use switch

If you want to control the flow depending on the type you can use the switch construction

func do(i interface{}) {
    switch v := i.(type) {
    case int:
        fmt.Printf("Twice %v is %v\n", v, v*2)
    case string:
        fmt.Printf("%q is %v bytes long\n", v, len(v))
    default:
        fmt.Printf("I don't know about type %T!\n", v)
    }
}

Use fmt package

If you want only to display its type you can always use the fmt package

i := 1000
fmt.Printf("The type is %T", i)
kabanek
  • 303
  • 3
  • 18
  • _"Using reflects is almost always a bad choice."_ I disagree with this. The `fmt` package also uses reflection to achieve the same. – icza Oct 26 '18 at 11:09
  • yes but this scenario you use it not directly. -> http://www.jerf.org/iri/post/2945. From the official blog you can find "Once you understand these laws reflection in Go becomes much easier to use, although it remains subtle. It's a powerful tool that should be used with care and avoided unless strictly necessary." – kabanek Oct 26 '18 at 13:57