简体   繁体   中英

How to use reflection to set nested struct field values

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM