Despite manipulating elements within a struct during loop iterations, the updates fail to persist upon exiting the loop. Understanding the reason behind this behavior is crucial for correct struct manipulation.
When iterating over a struct slice, the loop variable refers to a copy of the original element, not the element itself. So, any modifications made within the loop only affect the copy and not the actual element in the slice.
To successfully update the struct elements, the following approach can be used:
Here is an updated code snippet that follows the solution:
type FTR struct { Id string Mod []Mod } type Mod struct { Name string Type string } for index := range ftr.Mod { switch ftr.Mod[index].Type { case "aaa", "bbbb": ftr.Mod[index].Type = "cccc" case "htr": ftr.Mod[index].Type = "com" case "no": ftr.Mod[index].Type = "jnodejs" case "jdb": ftr.Mod[index].Type = "tomcat" } }
By adopting this approach, the struct elements will be successfully updated, and the changes will persist after the loop exits.
以上是為什麼我的結構更新在 Go 循環中不持久?的詳細內容。更多資訊請關注PHP中文網其他相關文章!