我想循环遍历一个结构并使用反射修改字段值。如何设置?
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() 会导致 panic 并显示: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))
}
}
关于go - 使用反射和循环修改结构体值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67260295/