【发布时间】:2017-03-04 08:46:04
【问题描述】:
我试图遍历结构的各个字段,将函数应用于每个字段,然后将原始结构作为一个整体返回,并带有修改后的字段值。 显然,如果是针对一个结构,这不会带来挑战,但我需要该函数是动态的。 对于这种情况,我引用 Post 和 Category 结构,如下所示
type Post struct{
fieldName data `check:"value1"
...
}
type Post struct{
fieldName data `check:"value2"
...
}
然后我有一个 switch 函数,它循环遍历结构的各个字段,并根据 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语句之后的修改值重新插入到上面示例中接口指定的结构中。
如果您需要其他任何东西,请告诉我。
谢谢
【问题讨论】:
标签: go reflection struct interface