我正在尝试遍历结构的各个字段,将一个函数应用于每个字段,然后将原始结构作为一个整体返回,并带有修改后的字段值。 显然,如果它是一个结构,这不会带来挑战,但我需要函数是动态的。 对于这个例子,我引用了 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 语句之后的修改值重新插入到上面示例中接口(interface)指定的结构中。
如果您还需要什么,请告诉我。
谢谢
最佳答案
变量 field
的类型为 reflect.Value
。调用Set* field
上的方法来设置结构中的字段。例如:
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())
...
}
此外,字段名称必须是 exported .
关于戈朗 : loop through fields of a struct modify them and and return the struct?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40186815/