【问题标题】:type reflection of pointer to struct in gogo中指向结构的指针的类型反射
【发布时间】:2021-01-26 12:08:51
【问题描述】:

当我只有一个指向结构的指针时,我无法确定结构的类型。

type TypeA struct {
  Foo string
}

type TypeB struct {
  Bar string
}

我必须实现以下回调:

func Callback(param interface{}) {

}

param 可以是*TypeA*TypeB

如何确定param 的类型?

reflect.TypeOf(param) 似乎不适用于指针。

当我这样做时

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

输出为空

提前感谢您的帮助。

【问题讨论】:

    标签: go pointers reflection


    【解决方案1】:

    *TypeA 等指针类型是 未命名 类型,因此查询它们的名称将为您提供空字符串。使用Type.Elem() 获取元素类型,并打印其名称:

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

    测试它:

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

    哪个会输出(在Go Playground上试试):

    TypeA
    TypeB
    

    另一种选择是使用Type.String() 方法:

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

    这将输出(在Go Playground 上尝试):

    *main.TypeA
    *main.TypeB
    

    查看相关问题:

    using reflection in Go to get the name of a struct

    Identify non builtin-types using reflect

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-19
      • 2013-12-13
      • 2021-10-16
      • 2019-03-18
      • 2021-04-01
      • 1970-01-01
      • 2021-01-18
      • 1970-01-01
      相关资源
      最近更新 更多