简体   繁体   中英

type reflection of pointer to struct in go

I'm having problems determine the type of a struct when I only have a pointer to the struct.

type TypeA struct {
  Foo string
}

type TypeB struct {
  Bar string
}

I have to implement the following callback:

func Callback(param interface{}) {

}

param can be *TypeA or *TypeB .

How can I determine the Type of param ?

reflect.TypeOf(param) seems not to work with a pointer.

When I do this

func Callback(param interface{}) {
  n := reflect.TypeOf(param).Name()
  fmt.Printf(n)
}

The output is empty

Thanks in advance for any help.

Pointer types such as *TypeA are unnamed types, hence querying their names will give you the empty string. Use Type.Elem() to get to the element type, and print its name:

func Callback(param interface{}) {
    n := reflect.TypeOf(param).Elem().Name()
    fmt.Println(n)
}

Testing it:

Callback(&TypeA{})
Callback(&TypeB{})

Which will output (try it on the Go Playground ):

TypeA
TypeB

Another option is to use the Type.String() method:

func Callback(param interface{}) {
    n := reflect.TypeOf(param)
    fmt.Println(n.String())
}

This will output (try it on the Go Playground ):

*main.TypeA
*main.TypeB

See related questions:

using reflection in Go to get the name of a struct

Identify non builtin-types using reflect

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM