Home >Backend Development >Golang >How to Modify Original Values During Range Iterations in Go?

How to Modify Original Values During Range Iterations in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-30 12:34:14575browse

How to Modify Original Values During Range Iterations in Go?

Addressing Values in Range Iterations

When iterating over a range of values, it's common to want to modify the original values rather than just working with copies. However, by default, the range construct returns a copy of each value.

package main

import "fmt"

type MyType struct {
    field string
}

func main() {
    var array [10]MyType

    for _, e := range array {
        e.field = "foo"
    }

    for _, e := range array {
        fmt.Println(e.field)
        fmt.Println("--")
    }
}

In the above code, the "field" field of each element in the array is not modified because the range copies the value into the e variable.

Solution

To modify the original values, you cannot use the range construct to iterate over the values. Instead, you must use the array index.

package main

import "fmt"

type MyType struct {
    field string
}

func main() {
    var array [10]MyType

    for idx, _ := range array {
        array[idx].field = "foo"
    }

    for _, e := range array {
        fmt.Println(e.field)
        fmt.Println("--")
    }
}

By using the array index, you are directly accessing the original values in the array and can modify them as needed.

The above is the detailed content of How to Modify Original Values During Range Iterations in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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