[英]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 using unaddressable value
您必须将可寻址值传递给 function。
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))
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.