How to Effectively Update Struct Values During Iteration
In this code snippet, we have a struct FTR with an array of Mod structs. We aim to update the Type field of Mod elements based on specific criteria within a loop. However, it appears that the changes made within the loop are not reflected in the FTR struct after the loop completes.
The Issue
The heart of the problem lies in the fact that when you iterate over a slice or array using the range keyword, you only get a copy of the element, not a reference to the original element. This means that any modifications you make to the element within the loop will only affect the copy, leaving the original element unchanged.
Solution: Iterating with Indices
To correctly update the elements of the struct, we need to iterate over their indices and modify the original elements rather than their copies. Here's the corrected code:
type FTR struct { Id string Mod []Mod } 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" } }
In this updated code, we iterate over the indices of the Mod array, and modify the Type field directly on the original FTR struct. By doing so, we ensure that the changes made within the loop are preserved when the loop completes.
The above is the detailed content of Why are Struct Values Not Updated During Iteration in Go?. For more information, please follow other related articles on the PHP Chinese website!