Golang:循环遍历struct的字段修改它们并返回struct?

时间:2016-10-21 23:38:25

标签: go reflection struct interface

我试图遍历结构的各个字段,将函数应用于每个字段,然后使用修改的字段值返回原始结构作为整体。 显然,如果是一个结构,这不会带来挑战,但我需要功能是动态的。 对于这个例子,我引用了Post和Category结构,如下所示

type Post struct{
    fieldName           data     `check:"value1"
    ...
}

type Post struct{
    fieldName           data     `check:"value2"
    ...
}

然后我有一个循环遍历结构的各个字段的开关函数,并根据check具有的值,将函数应用于该字段的data,如下所示

type Datastore interface {
     ...
}

 func CheckSwitch(value reflect.Value){
    //this loops through the fields
    for i := 0; i < value.NumField(); i++ { // iterates through every struct type field
        tag := value.Type().Field(i).Tag // returns the tag string
        field := value.Field(i) // returns the content of the struct type field

        switch tag.Get("check"){
            case "value1":
                  fmt.Println(field.String())//or some other function
            case "value2":
                  fmt.Println(field.String())//or some other function
            ....

        }
        ///how could I modify the struct data during the switch seen above and then return the struct with the updated values?


}
}

//the check function is used i.e 
function foo(){ 
p:=Post{fieldName:"bar"} 
check(p)
}

func check(d Datastore){
     value := reflect.ValueOf(d) ///this gets the fields contained inside the struct
     CheckSwitch(value)

     ...
}   

本质上,如何将CheckSwitch中的switch语句之后的修改后的值重新插入到上例中接口指定的结构中。 如果您还有其他需要,请告诉我。 感谢

1 个答案:

答案 0 :(得分:2)

变量field的类型为reflect.Value。调用field上的Set*方法来设置结构中的字段。例如:

 field.SetString("hello")

将struct字段设置为“hello”。

如果要保留值,则必须将指针传递给结构:

function foo(){ 
    p:=Post{fieldName:"bar"} 
    check(&p)
}

func check(d Datastore){
   value := reflect.ValueOf(d)
   if value.Kind() != reflect.Ptr {
      // error
   }
   CheckSwitch(value.Elem())
   ...
}

此外,字段名称必须为exported

playground example