[英]How to use Golang Reflection to get the type of a struct field that is a slice?
[英]How to use reflection to set nested struct field values
我正在使用 Go 创建嵌套结构并填充它。 我在结构中有一个需要自己设置的自定义字段,但它是在外部结构的字段中使用的类型。 例如:
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"`
}
我创建了一个嵌套结构。 我想在我的程序中使用 Case 结构更新KitStatus
字段。意味着如果我从中访问 Case 结构,我如何移动到Kit_Details
结构并更新结构的字段。 有人可以帮助我如何使用FieldByName("KitStatus")
和使用SetString("New value")
循环遍历 Case 结构的字段来更新该字段的值。
你可以这样使用:
v := reflect.ValueOf(test)
fmt.Println("Value of test before update", v)
v.FieldByName("Kit_Details").Index(0).FieldByName("KitStatus").SetString("abcdsdf")
您可以使用循环遍历所有元素并使用Index()
更新它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.