我在 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/