[英]How to use reflection to set nested struct field values
I'm using Go to create a nested struct and populate it.我正在使用 Go 创建嵌套结构并填充它。 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.我想在我的程序中使用 Case 结构更新KitStatus
字段。意味着如果我从中访问 Case 结构,我如何移动到Kit_Details
结构并更新结构的字段。 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.有人可以帮助我如何使用FieldByName("KitStatus")
和使用SetString("New value")
循环遍历 Case 结构的字段来更新该字段的值。
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()
.您可以使用循环遍历所有元素并使用Index()
更新它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.