使用反射和循环修改结构值

Modifying struct value using reflection and loop

我想遍历结构并使用反射修改字段值。如何设置?

func main() {
    x := struct {
        Foo string
        Bar int
    }{"foo", 2}
    StructCheck(Checker, x)
}

func Checker(s interface{}) interface{} {
    log.Println(s)
    return s
}

func StructCheck(check func(interface{}) interface{}, x interface{}) interface{} {
    v := reflect.ValueOf(x)
    for i := 0; i < v.NumField(); i++ {
        r := check(v.Field(i))
        w := reflect.ValueOf(&r).Elem()

        log.Println(w.Type(), w.CanSet())

        // v.Field(i).Set(reflect.ValueOf(w))

    }
    return v
}

运行 Set() 导致恐慌并显示:reflect.Value.Set 使用无法寻址的值

您必须将可寻址值传递给该函数。

StructCheck(Checker, &x)

取消引用 StructCheck 中的值:

v := reflect.ValueOf(x).Elem() // Elem() gets value of ptr

还有一些其他问题。这是更新后的代码:

func StructCheck(check func(interface{}) interface{}, x interface{}) {
    v := reflect.ValueOf(x).Elem()
    for i := 0; i < v.NumField(); i++ {
        r := check(v.Field(i).Interface())
        v.Field(i).Set(reflect.ValueOf(r))

    }
}

Run it on the Playground.