Why Aren\'t My Struct Updates Persistent in a Go Loop?

DDD
Release: 2024-11-15 11:33:02
Original
511 people have browsed it

Why Aren't My Struct Updates Persistent in a Go Loop?

Update Value in Struct Not Working

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.

The Issue

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.

The Solution

To successfully update the struct elements, the following approach can be used:

  • Iterate over the indices instead of the slice: By iterating over the indices, direct access to the actual struct element is obtained. This allows for modifications that persist beyond the loop.
  • Avoid pointers: Pointers to slices or elements are unnecessary when updating values. The slice can be accessed directly, and elements can be updated without the need for pointers.

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"
    }
}
Copy after login

By adopting this approach, the struct elements will be successfully updated, and the changes will persist after the loop exits.

The above is the detailed content of Why Aren\'t My Struct Updates Persistent in a Go Loop?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template