Is it possible to update an attribute in a struct based?
Would it be possible to do it based on its JSON tag?
Supposing a simple structure:
type User struct {
Name string `json:"username"`
}
I need to update the Name
attribute programmatically using reflection. I tried the following:
user := User{Name: "John"}
obj := reflect.Indirect(reflect.ValueOf(user))
obj.FieldByName("Name").SetString("Jake")
panic: reflect: reflect.Value.SetString using unaddressable value
https://play.golang.org/p/gkBgRXwje57
To get an addressable value, pass the address of user
to reflect.ValueOf
:
user := User{Name: "John"}
obj := reflect.Indirect(reflect.ValueOf(&user))
obj.FieldByName("Name").SetString("Jake")
fmt.Println(user.Name)
It's known that the value is a pointer in this case, so call Elem() directly:
user := User{Name: "John"}
obj := reflect.ValueOf(&user).Elem()
obj.FieldByName("Name").SetString("Jake")
fmt.Println(user.Name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With