Col*_*sen 5 reflection struct interface go
我试图循环遍历结构体的各个字段,将函数应用于每个字段,然后将原始结构体作为一个整体与修改后的字段值返回。显然,如果对于一个结构来说这不会构成挑战,但我需要该函数是动态的。对于本例,我引用 Post 和 Category 结构,如下所示
type Post struct{
fieldName data `check:"value1"
...
}
type Post struct{
fieldName data `check:"value2"
...
}
Run Code Online (Sandbox Code Playgroud)
然后,我有一个开关函数,它循环遍历结构的各个字段,并根据其具有的值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)
...
}
Run Code Online (Sandbox Code Playgroud)
本质上,我如何将 switch 语句后修改的值重新插入CheckSwitch到上例中接口指定的结构中。如果您还需要什么,请告诉我。谢谢
该变量的field类型为reflect.Value。调用Set*方法来field设置结构中的字段。例如:
field.SetString("hello")
Run Code Online (Sandbox Code Playgroud)
将结构体字段设置为“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())
...
}
Run Code Online (Sandbox Code Playgroud)
另外,字段名称必须导出。