Home > Backend Development > Golang > Why Does My Go Range Loop Not Modify Array Elements?

Why Does My Go Range Loop Not Modify Array Elements?

Barbara Streisand
Release: 2024-12-17 18:47:11
Original
278 people have browsed it

Why Does My Go Range Loop Not Modify Array Elements?

Returning Addresses instead of Values for Range References

Consider the situation where a range statement returns a copy of a value instead of the original address. This can lead to unexpected behavior, as seen in the following Go code:

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

In this example, the intent is to modify the "field" property of each element in the array. However, since the range statement returns a copy of the value, the changes are made to a local copy and don't affect the original array. As a result, the output shows all "field" properties as having the default value.

To address this issue, you cannot return the address of the item in a range loop. Instead, you should iterate through the array using the index, as shown below:

func main() {
    var array [10]MyType

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

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

By using the index instead of the value in the for loop, you ensure that the changes made to the "field" property are reflected in the original array.

The above is the detailed content of Why Does My Go Range Loop Not Modify Array Elements?. 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