jeudi 1 février 2018

Update an attribute in a struct with reflection

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





Aucun commentaire:

Enregistrer un commentaire