douju6542 2018-03-07 22:40
浏览 110
已采纳

使用反射来遍历struct的struct成员并在其上调用方法

I have a struct that has one or more struct members. Each member is expected to implement a Validator interface.

I want to use reflection to iterate over all struct members and call the interface's Validate() method. For example:

package main

import "fmt"
import "reflect"

type Validator interface {
    Validate()
}

type T1 struct {
    S string
}

func (p *T1) Validate() {
    fmt.Println("HERE 1")
}

type T2 struct {
    S string
}

func (p *T2) Validate() {
    fmt.Println("HERE 2")
}

type Top struct {
    S1 T1
    S2 T2
}

func main() {
    var t Top

    r := reflect.ValueOf(t)
    for i := 0; i < r.NumField(); i++ {
        f := r.Field(i)
        if f.Kind() == reflect.Struct {
            validator := f.Interface().(Validator)
            validator.Validate()
        }
    }
}

When run, it outputs:

panic: interface conversion: main.T1 is not main.Validator: missing method Validate

If I change the Validate() methods to accept value (rather than pointer) receivers, then it works. However, I want to use pointer receivers since the structs may grow to be large.

How can I change the reflection code to work where the methods are defined taking pointer receivers?

I also tried using this line:

            validator := f.Addr().Interface().(Validator)

to get a pointer, but it then outputs:

panic: reflect.Value.Addr of unaddressable value

  • 写回答

2条回答 默认 最新

  • drkug66408 2018-03-07 22:47
    关注

    None of your values are addressable, so you can't call any methods on them with pointer receivers.

    If the S1 and S2 fields can't be pointers, you can still address them if you have a pointer to the Top struct:

    r := reflect.ValueOf(&t).Elem()
    for i := 0; i < r.NumField(); i++ {
        f := r.Field(i)
        if f.Kind() == reflect.Struct {
            validator := f.Addr().Interface().(Validator)
            validator.Validate()
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”