Add values indirect to nested struct

Viewed 94

i setup a nested struct in Golang and i want to fill it with values indirect.

type Categories struct {
    A ABCDE `json:"A"`
    B ABCDE `json:"B"`
    C ABCDE `json:"C"`
    D ABCDE `json:"D"`
    E ABCDE `json:"E"`
}

type ABCDE struct {
    Foo string `json:"foo`
}

Direct is working of course:

categories:= Categories{}
Categories.A.Foo = "Salute"

Indirect as pseudo code:

categories:= Categories{}
Categories.["A"].Foo = "Salute"

Direct solution is of course no problem. Is there a way to implement the indirect solution, that i am able to put the nested object inside as parameter?

1 Answers

You can use reflection (reflect package).

categories:= Categories{}
reflect.ValueOf(&categories).
    Elem().
    FieldByName("A").
    FieldByName("Foo").SetString("Salute")

PLAYGROUND

Related