首頁  >  文章  >  後端開發  >  為什麼我的結構更新在 Go 循環中不持久?

為什麼我的結構更新在 Go 循環中不持久?

DDD
DDD原創
2024-11-15 11:33:02504瀏覽

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

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

以上是為什麼我的結構更新在 Go 循環中不持久?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn