Home >Backend Development >Golang >How to Update Nested Struct Values in Go?
Updating Struct Values in Go
In Go, structs are value types, which means that assigning one struct to another copies its values rather than creating a reference. This can lead to unexpected behavior when trying to modify values within a nested struct.
Consider the following code snippet:
ftr := FTR{} err := yaml.Unmarshal([]byte(yamlFile), &ftr) for index, element := range ftr.Mod { switch element.Type { case "aaa", "bbbb": element.Type = "cccc" case "htr": element.Type = "com" case "no": element.Type = "jnodejs" case "jdb": element.Type = "tomcat" } }
The intention is to update the Type field of each Mod element in the ftr struct based on a series of conditions. However, after the code has executed, the Type field of each element remains unchanged.
This behavior is caused by the fact that the range loop iterates over a copy of the ftr.Mod slice. Consequently, any modifications made to the element variable within the loop are not reflected in the original ftr.Mod slice.
To resolve this issue and correctly update the values in the ftr struct, you can use index-based iteration instead of ranging over the slice. This allows you to modify the values directly in the original slice:
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" } }
By iterating over the indices of the ftr.Mod slice and directly modifying the corresponding elements, you ensure that the original ftr struct is updated as intended.
The above is the detailed content of How to Update Nested Struct Values in Go?. For more information, please follow other related articles on the PHP Chinese website!