【问题标题】:Golang: loop through fields of a struct modify them and and return the struct?Golang:遍历结构的字段修改它们并返回结构?
【发布时间】: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


    【解决方案1】:

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

     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

    【讨论】:

    • 您好,感谢您的回答!设置字段值后,我是否需要返回reflect.Value?在这种情况下,我如何将其重新插入到指定的结构中,即Post 以供进一步使用?
    猜你喜欢
    • 2021-12-24
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多