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
",
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?
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
", (*X)(nil), something)
Output will be (try it on the Go Playground):
Expecting type *main.X, got struct {}
Using reflects is almost always a bad choice. You can consider using one of the following ways
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
", v, v*2)
case string:
fmt.Printf("%q is %v bytes long
", v, len(v))
default:
fmt.Printf("I don't know about type %T!
", v)
}
}
fmt
packageIf you want only to display its type you can always use the fmt
package
i := 1000
fmt.Printf("The type is %T", i)