Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 685
Arkon Avatar asked Dec 23 '22 10:12

Arkon


1 Answers

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)
like image 200
Bayta Darell Avatar answered Jan 07 '23 16:01

Bayta Darell