1

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.