Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 调用方法属于结构的字段_Go_Reflection_Struct - Fatal编程技术网

Go 调用方法属于结构的字段

Go 调用方法属于结构的字段,go,reflection,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+

我在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
}
func validateStruct(接口{})错误{
v:=反射值(a)
t:=反射类型(a)
对于i:=0;i

但这会引起很多恐慌

我发现了问题。
reflect.TypeOf(v.Field(i.Interface()).MethodByName(“Validate”)
仅当验证函数没有指针接收器时才能查看该函数,因此如果我将string128的验证函数修改为
func(s string128)Validate()错误
,则该函数正在工作

最终解决方案

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
}
func validateStruct(接口{})错误{
v:=反射值(a)
对于i:=0;i