Golang:循环遍历结构体字段,修改它们并返回结构体?

5

我想循环遍历结构体的每个字段,对每个字段应用一个函数,然后将修改后的字段值作为整个结构体返回。 显然,如果只针对一个结构体,这并不是什么难题,但我需要这个函数是动态的。 在这个例子中,我引用了如下所示的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语句中修改过的值重新插入到接口指定的结构体中?请让我知道您是否还需要其他帮助。谢谢。

1个回答

4
变量 field 的类型是 reflect.Value。调用 field 上的 Set* 方法来设置结构体中的字段。例如:
 field.SetString("hello")

将结构体字段设置为"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())
   ...
}

此外,字段名称必须是导出的示例代码

嘿,感谢您的回答!在设置字段值之后,我是否需要返回reflect.Value?我该如何重新将其插入到指定的结构体中,例如在这种情况下是Post,以供进一步使用? - Colleen Larsen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接