在不使用反射的情况下打印类型并创建新对象

问题描述:

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?

在下面的代码中,为了显示预期的类型,我必须创建一个新对象并调用 p>

  package main 
 
import(
“ fmt” 
“ reflect  “ 
)
 
type X struct {
 name string 
} 
 
func check(something interface {}){
 if _,ok:= something。(* X);  !ok {
 fmt.Printf(“期望类型%v,得到%v 
”,
 Reflection.TypeOf(X {}),reflect.TypeOf(something))
} 
} 
 
func  main()
 check(struct {} {})
} 
  code>  pre> 
 
 

也许创建对象不是开销,但我仍然想知道一个更好的方法 方式。 在Java中是否有类似 X.getName() code>或 X.getSimpleName() code>的东西? p> div>

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

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
", 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)
    }
}

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)