0
votes

I'm using Go to create a nested struct and populate it. I have a custom field in the struct that I need to set myself, but it's a type used in a field of the outer struct. For example:

type Case struct {
   CaseID            string         `json:"caseID"`
   CaseStatus        string         `json:"caseStatus"`
   Kit_Details       []Kit_Details  `json:"kit_Details"`
}

type Kit_Details struct {
    KitID          string    `json:"kitID"`
    KitStatus      string    `json:"kitStatus"`
}

I have created a nested struct. I want to update KitStatus fields using Case struct in my program.Means if I access Case struct from that how can i move to Kit_Details struct and update the field of a structure. Can somebody help me how to loop through the fields of Case struct using FieldByName("KitStatus") and using SetString("New value") to update the value of that field.

1
If the type is already known, why do you need reflection?bereal
The Kit_Details field is a slice, you can use golang.org/pkg/reflect/#Value.Len and golang.org/pkg/reflect/#Value.Index to loop over the elements of the slice.mkopriva

1 Answers

1
votes

You can use like this:

v := reflect.ValueOf(test)
fmt.Println("Value of test before update", v)
v.FieldByName("Kit_Details").Index(0).FieldByName("KitStatus").SetString("abcdsdf")

You can use a loop to traverse all the elements and update them using Index().

Go play ground link