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条)

报告相同问题?

悬赏问题

  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致