go - 调用方法属于struct的字段

标签 go reflection struct

我在 Golang 中有一些特殊类型,它代表一个带有 Validate 方法的字符串。

type string128 string

func (s *string128) Validate() error {
    ...
    return nil
}

有些结构具有如下字段:

type Strings1 struct {
    str1 string
    str2 string128
    str3 string128
    ...
    strN+1 string128
    strN+2 string
}

type Strings2 struct {
    str1 string
    str2 string128
    str3 string128
    ...
    strN+1 string128
    strN+2 string
}

我想创建一个函数,我可以在其中传递它们,如果该字段有 Validate() 函数,则调用它。

我做了什么:

func validateStruct(a interface{}) error {
    v := reflect.ValueOf(a)
    t := reflect.TypeOf(a)
    for i := 0; i < v.NumField(); i++ {
        err := reflect.TypeOf(v.Field(i).Interface()).MethodByName("Validate").Call(...)
    }
    return nil
}

但它确实造成了很多 panic 。

最佳答案

我发现了问题。 reflect.TypeOf(v.Field(i).Interface()).MethodByName("Validate") 仅当 Validate 函数没有指针接收器时才会看到该函数,因此如果我修改 Validate string128 到 func (s string128) Validate() error 的函数,它正在工作。

最终解决方案

func validateStruct(a interface{}) error {
    v := reflect.ValueOf(a)
    for i := 0; i < v.NumField(); i++ {
        if _, ok := reflect.TypeOf(v.Field(i).Interface()).MethodByName("Validate"); ok {
            err := reflect.ValueOf(v.Field(i).Interface()).MethodByName("Validate").Call([]reflect.Value{})
            if !err[0].IsNil() {
                return err[0].Interface().(error)
            }
        }
    }
    return nil
}

关于go - 调用方法属于struct的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46216259/

相关文章:

go - 结构映射不保存键/值

c# - 使用 Linq 表达式设置一个 readoly/InitOnly 成员字段

c - 清除内存的结构体和Free函数: C Programming

file - 如何在 Octave 中使用变量文件名将结构保存到文件中?

go - 访问 URL 时终止 go routine

go - 别名转换

class - GO接口(interface)中的多态性

c# - CreateDelegate 而不是 SetValue 的反射

c# - 你如何从堆栈框架中获取通用参数的类型?

c - 尝试创建一个结构数组并从文件加载数据