戈朗 : loop through fields of a struct modify them and and return the struct?

标签 go reflection struct interface

我正在尝试遍历结构的各个字段,将一个函数应用于每个字段,然后将原始结构作为一个整体返回,并带有修改后的字段值。 显然,如果它是一个结构,这不会带来挑战,但我需要函数是动态的。 对于这个例子,我引用了 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 .

playground example

关于戈朗 : loop through fields of a struct modify them and and return the struct?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40186815/

相关文章:

sql - 如何确定我正在使用的数据库驱动程序的名称?

go - 在 Go 中读取 gzipped HTTP 响应

c# - 使用反射设置对象属性

swift - 来自枚举的类参数

postgresql - Golang GORM 中列的自动迁移问题

macos - RabbitMQ Go 教程日志.Printf 无法写入磁盘文件?

c# - 如何在运行时将方法附加到动态创建的 C# 类型?

java - 在最终公共(public)类Java中修改最终静态变量

c++ - 静态常量对象

delphi - 在运行时获取delphi记录中字段的偏移量