gofrm
gofrm

Reputation: 416

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.

Upvotes: 1

Views: 428

Answers (1)

icza
icza

Reputation: 417462

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

Upvotes: 2

Related Questions