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

Go 使用反射和循环修改结构值,go,reflection,Go,Reflection,我想循环一个结构并使用反射修改字段值。我如何设置它 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 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
}
func main(){
x:=struct{
Foo字符串
Bar int
}{“foo”,2}
结构检查(检查器,x)
}
函数检查器(s接口{})接口{}{
log.Println(s)
返回s
}
func StructCheck(check func(interface{})interface{},x interface{})interface{}{
v:=反射值(x)
对于i:=0;i

运行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))

    }
}
func结构检查(检查func(接口{})接口{},x接口{}){
v:=reflect.ValueOf(x).Elem()
对于i:=0;i

.

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

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))

    }
}
func结构检查(检查func(接口{})接口{},x接口{}){
v:=reflect.ValueOf(x).Elem()
对于i:=0;i

.

但当我试图将其转换到x的结构时,它再次恐慌,是否有办法修复此问题@ned我编辑了答案以从StructCheck中删除返回值。因为调用者已经有了这个值,所以不需要从返回值中再次获取这个值。但是当我试图将它转换到x的结构时,它会再次陷入恐慌,有没有办法解决这个问题@ned我编辑了答案以从StructCheck中删除返回值。因为调用者已经拥有该值,所以不需要从返回值中再次获取该值。