我试图遍历将函数应用于每个字段的结构的各个字段,然后将原始结构作为整体与修改后的字段值一起返回。
显然,如果只针对一个结构,这将不是一个挑战,但是我需要函数是动态的。
对于这种情况,我引用了Post和Category结构,如下所示

1
2
3
4
5
6
7
8
9
type Post struct{
    fieldName           data     `check:"value1"
    ...
}

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

然后,我有了一个switch函数,该函数遍历结构的各个字段,并根据check的值,对该字段的data应用一个函数,如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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语句之后将修改后的值重新插入上例中接口指定的结构中。
如果您还有其他需要,请告诉我。
谢谢


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

1
 field.SetString("hello")

将struct字段设置为" hello"。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
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)中?