dqly83915 2019-03-29 02:03
浏览 177
已采纳

如何遍历reflect.TypeOf(interface {})上的* T func?

I'm having a few problems iterating through *T funcs from a struct using reflect.

I've searched a lot of answers but none seems to talk specifically about this situation.

I've found a reflect.NewAt at golang documentation but to be honest I didn't understand, and again I couldn't find a single answer for my situation.

For a better understanding... by having the following struct:

type Counter struct {}
func (self *Counter) Add(n int) {}

If I use reflect by calling the struct pointer itself, it works as expected:

y := reflect.TypeOf(&Counter{})

for k := 0; k < y.NumMethod(); k++ {
    fmt.Println(y.Method(k)) // {Add  func(*Counter, int) <func(*Counter, int) Value> 0}
}

But in my case, multiple structs can arrive here, so it arrives as an interface:

var p interface{} = Counter{}

z := reflect.New(reflect.TypeOf(p))

for k := 0; k < z.NumMethod(); k++ {
   fmt.Println(z.Method(k)) // 0x47d150
}

But as shown, it prints the memory address.

I expect the 0x47d150 to be the same output as I was using the pointer directly. What I'm doing wrong here?

  • 写回答

1条回答 默认 最新

  • dpbsy60000 2019-03-29 04:54
    关注

    The value y a reflect.Type. The Method method on a type is the equivalent of a method expression.

    The value z is a reflect.Value. The Method method on a value is the equivalent of a method value.

    The printed representation is different because method expressions and method values are not the same thing.

    Use reflect.PtrTo to get pointer type for a type:

    var p interface{} = Counter{}
    z := reflect.PtrTo(reflect.TypeOf(p))
    for k := 0; k < z.NumMethod(); k++ {
        fmt.Println(z.Method(k))  // {Add  func(*Counter, int) <func(*Counter, int) Value> 0}
    }
    

    The concrete value in the interface is a non-pointer value. You can use this code if the concrete value in the interface is the pointer type:

    var p interface{} = &Counter{}
    z := reflect.TypeOf(p)
    for k := 0; k < z.NumMethod(); k++ {
        fmt.Println(z.Method(k)) // {Add  func(*Counter, int) <func(*Counter, int) Value> 0}
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog