I wanted to loop through a struct and modify fields value using reflection. How can I Set it?
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
}
Running Set() causes panic and shows :reflect.Value.Set using unaddressable value
Aucun commentaire:
Enregistrer un commentaire