Home > Backend Development > Golang > Why are Struct Values Not Updated During Iteration in Go?

Why are Struct Values Not Updated During Iteration in Go?

Susan Sarandon
Release: 2024-12-09 13:14:15
Original
789 people have browsed it

Why are Struct Values Not Updated During Iteration in Go?

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"
    }

}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template