简体   繁体   English

go中结构指针的类型反射

[英]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 . param可以是*TypeA*TypeB

How can I determine the Type of param ?如何确定param的类型?

reflect.TypeOf(param) seems not to work with a pointer. reflect.TypeOf(param)似乎不适用于指针。

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.诸如*TypeA类的指针类型是未命名的类型,因此查询它们的名称将为您提供空字符串。 Use Type.Elem() to get to the element type, and print its name:使用Type.Elem()获取元素类型,并打印其名称:

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 ):哪个将输出(在Go Playground上尝试):

TypeA
TypeB

Another option is to use the Type.String() method:另一种选择是使用Type.String()方法:

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

This will output (try it on the Go Playground ):这将输出(在Go Playground上尝试):

*main.TypeA
*main.TypeB

See related questions:查看相关问题:

using reflection in Go to get the name of a struct 在 Go 中使用反射来获取结构的名称

Identify non builtin-types using reflect 使用反射识别非内置类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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